0

OK I'm not good at Regex. I want to split with delimiter ' while keeping it. What I want as output is

(3) ["'", "TEST", "'"]

When I use:

"'TEST'".split(/(['])/g);

Instead I get:

(5) ["", "'", "TEST", "'", ""]

It's almost what I want except I also get 2 empty strings. Why ?

2
  • maybe like this ? "'TEST'".replace(/([a-zA-Z]+)/g, "\n$1\n").split(/\n/) Commented Apr 12, 2020 at 18:51
  • @D.Seah thanks maybe usefull also. Commented Apr 12, 2020 at 19:32

3 Answers 3

1

The regex seems to be overkill for this purpose. Something like this works:

"'TEST'".split("'").map(str => (str.length) ? str : "'");
// [ "'", 'TEST', "'" ]
Sign up to request clarification or add additional context in comments.

Comments

1

You end up with two empty strings in your array because the first ' character separates an empty string at the beginning from the string TEST, while the second ' character separates the string TEST from another empty string at the end.


You can just use String.prototype.match() instead of String.prototype.split():

console.log("'TEST'".match(/'|[^']+/g));

Make sure you check for a null return value from .match(), but that is only possible with this particular regular expression when applied to an empty string.

1 Comment

Good suggestion, will try if it can cope with all my use cases.
0

You could do the trick by using a positive lookahead and lookbehind:

> "'TEST'".split(/(?<=')(.+)(?=')/g)
["'", "TEST", "'"]

Comments

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.