Home > database >  How can I split a string into words with JavaScript starting at a particular character, and then end
How can I split a string into words with JavaScript starting at a particular character, and then end

Time:09-04

I'd have a string that is something along the lines of:

"This is a string. $This is a word that has to be split. There could be $more than one in a string."

And I want to split it into an array so it ends up like this:

["This is a string. ", "$This", " is a word that has to be split. There could be ", "$more", " than one in a string."]

So basically, I need to have them split on '$' until just before the next space. I would also like to keep the spaces in the other strings if possible. Is there a way to do this with split() or would regex need to be used here?

CodePudding user response:

You could split on \$[^ ] which matches a $ sign followed by some number of non-space characters. By putting the regex into a capturing group we ensure the split strings also end up in the output array:

const str = "This is a string. $This is a word that has to be split. There could be $more than one in a string."

console.log(str.split(/(\$[^ ] )/))

CodePudding user response:

The regex pattern \B\$\w should do the trick for you.

const str = "This is a string. $This is a word that has to be split. There could be $more than one in a string.";

console.log(str.split(/(\B\$\w )/g));

  • Related