-2

I've created 2 functions here, and they're nearly 100% identical. The only difference is that the functions' regex character sets are ordered differently. Why do these 2 functions result in different outputs?

// FUNCTION 1:
function splitify(str) {
  let divs= str.split(/[\." "-,]/)    //order different [inside]
  return divs
}
console.log(splitify("Hello World,I-am code")); 
 //OUTPUT: ["Hello", "World", "I-am", "code"]
//FUNCTION 2
function splitify2(str) {
  let divs = str.split(/[-" ",\.]/);   //order different [inside]
  return divs;
}
console.log(splitify2('Hello World,I-am code'));
//OUTPUT: ['Hello', 'World', 'I', 'am', 'code'];
  • Note that `[\." "-,]` (or simplified `[. "-,]`) matches any of `"#$%&'()*+,.` or space, while `[-" ",\.]` (or simplified `[-" ,.]`) matches any of `",-.` or space. – Biffen Apr 08 '21 at 06:08

1 Answers1

3

The regex structure inside brackets is slightly different.

For example, when you try to match the string -. the regex should be /-\./ because . represents any single char and should be escaped in order to be literal.

However, using brackets enables you to look for literals but in there it's the - that is different. for example, [a-z] means the range from a to z, therefore you need to escape it for it to be considered as literal.

So, your syntax /[\." "-,]/should be like this /[. \-,]/.

Note that . doesn't need to be escaped, and also the space is like any other char and doesn't need quotes.

Gil
  • 1,794
  • 1
  • 12
  • 18