What is the regex form of '' in the split function in javascript

Viewed 213

How can I replace .split('') with a regex function resulting the same output

The closest I can think of is \w which selects by letter. But the issue here being, split deletes everything being selected.

eg: I have a string abcd, performing .split('') gives me ['a', 'b', 'c', 'd'] but .split(/\w/) gives me ['', '', '', '']

2 Answers

You can use a zero-width lookahead to make sure there is at least a character ahead:

var s='abcd-123'
console.log( s.split(/(?=.)/) )
//=> [a, b, c, d, -, 1, 2, 3]

If you really wanted to use a regular expression and split, consume no characters in the match, while making sure you're not at the beginning or end of the string, by negative lookaround for ^ and $:

console.log(
  'abcd'.split(/(?!^|$)/)
);

But if you needed to solve this with a regex, consider using .match instead, I think the intent is a lot clearer:

console.log(
  'abcd'.match(/[\s\S]/g)
);

Related