Separate using javascript

below is what i am trying to do with javascript.

If I have a line like

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

now i want to smash it? (or. or!), but I do not want to lose the "?". Instead, I want to break the line immediately after the question mark so that the question mark is with the first segment that we have. also after? or or! in order to break it into segments

should be \ s (space)
 after splitting str what should I get is ["how are you?","hope you are doing good"] 

I'm not sure if this can be done using the Javascript split () function, please help.

+4
source share
6 answers
 str.match(/\S[^?]*(?:\?+|$)/g) ["how are you?", "hope you are doing good"] 
+10
source

The easiest, most direct way I see is simply to 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] += "?"; } 

Alternatively, however, there is a path through RegExp. Edit Deleted mine, regex S.Mark is much better.

+4
source

One option is to use a regular expression, for example:

 str = "how are you? hope you are doing good"; var tokens = str.split(/(\?)/) 

but this will lead to question marks in their own token: how are you,?, hope you are,?, doing good

The best way:

 var tokens = str.match(/[^?]+\?*/g) 

It will also contain a few question marks: "hello??? how are you?"

+2
source

...

 var str = "how are you? hope you are doing good"; var data = str.split('?'); data[0] += '?'; alert(data[0]); // result: how are you? alert(data[1]); // result: hope you are doing good 
+1
source

If JS supports regexp look-behinds, everything you need is split into /(?<=\?)/ , But unfortunately this does not happen. However, you can easily get the same behavior with the match() function:

 var str = "how are you? hope you are doing good"; var data = str.match(/(?!$)[^?]*\??/g); 

You will receive ["how are you?", " hope you are doing good"]

+1
source

another idea:

 var str = "how are you? hope you are doing good", strsplit = str.split('?').join('?#').split('#'); alert(strsplit) //=> how are you?, hope you are doing good 

or (based on response and comments from kobi )

 var str = "how are you? All right?? Hope so???"; alert(str.replace(/([\?(1,}][^\?$])/g,'$1#!#').split(' #!#')); //=>how are you?,All right??,Hope so??? 
+1
source

Source: https://habr.com/ru/post/1309519/


All Articles