Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split with javascript

below is something I am trying to do with JavaScript.

If I have string like

str = "how are you? hope you are doing good" ;

now I want to split it with ? (or . or !) but I dont want to lose the "?". Instead I want to break the string just after the question mark such a way that question mark is with the first segment that we have. also after the ? or / or ! there needs to be a \s (space) in order to break it into segments

after splitting str what should I get is

["how are you?","hope you are doing good"]

I am not sure if it can be done with Javascript split() function ,please help.

like image 284
Sourabh Avatar asked Nov 30 '22 05:11

Sourabh


2 Answers

str.match(/\S[^?]*(?:\?+|$)/g)

["how are you?", "hope you are doing good"]
like image 54
YOU Avatar answered Dec 09 '22 17:12

YOU


The easiest, most straight-forward way I can see is to just lose the "?" and add it back:

var parts, n;
parts = str.split("?");
for (n = parts.length - 2; n >= 0; --n) { // Skip the last one
    parts[n] += "?";
}
if (str.charAt(str.length-1) == "?") {    // If it ended with "?", add it back
    parts[parts.length-1] += "?";
}

Alternately, though, there's a way via RegExp. Edit Removed mine, S.Mark's regex is so much better.

like image 32
T.J. Crowder Avatar answered Dec 09 '22 17:12

T.J. Crowder