-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'];
1
  • Note that [\." "-,] (or simplified [. "-,]) matches any of "#$%&'()*+,. or space, while [-" ",\.] (or simplified [-" ,.]) matches any of ",-. or space. Commented Apr 8, 2021 at 6:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.