0

I would like to split a string of text into an array of sentences without loosing the punctuation mark.

var string = 'This is the first sentence. This is another sentence! This is a question?' 
var splitString = string.split(/[!?.] /);
splitString  
  => ["This is the first sentence", "This is another sentence", "This is a question?"]

Only the last punctuation mark(?) is kept. What is the best way to split after the punctuation marks on all the sentences so that splitString returns the following instead?

["This is the first sentence.", "This is another sentence!", "This is a question?"]
3

2 Answers 2

3

Instead of using split to target where you want to break your text, you can use String#match with a global regular expression and target the text you want to keep:

var splitString = string.match(/\S.+?[!?.]/g)

This avoids the need to use look-behinds, which are unsupported in JavaScript's regex flavor as of now, or additional calls to methods like Array#filter:

var string = 'This is the first sentence. This is another sentence! Is this a question?'

var splitString = string.match(/\S.+?[!?.]/g)

console.log(splitString)

Sign up to request clarification or add additional context in comments.

Comments

1

Few approaches:

The solution using String.prototype.match() function to get an array of sentences:

var string = 'This is the first sentence. This is another sentence! This is a question?',
    items = string.match(/\S[^.!?]+[.?!]/g);

console.log(items);

The alternative solution using String.prototype.split() function would look like below:

var string = 'This is the first sentence. This is another sentence! This is a question?',
    items = string.split(/(\S[^.!?]+[.?!])/g).filter(function(s){ return s.trim(); });

console.log(items);

\S[^.!?]+ - will match all characters except specified punctuation chars [^.!?] and starting with non-whitespace character \S

4 Comments

Note that this also matches a leading space at the beginning of some sentences.
@gyre, can't agree with you
I see you edited your answer so this is no longer an issue. It was such a small window I did not get a chance to see the changes before commenting :)
@gyre, yes, I've made the edit right before your comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.