-1

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?

wendigo
  • 59
  • 6

2 Answers2

2

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(/(\$[^ ]+)/))
Nick
  • 138,499
  • 22
  • 57
  • 95
0

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));
Rahul Sharma
  • 5,562
  • 4
  • 24
  • 48