Question about the use of parameters in join() and split()

Hi Can anyone please explain what it means if you have join(‘|’) or split(‘|’) if you are trying to split or join a string? Thank you

please see below context:

sorted=words.join(‘|’).toLowerCase().split(‘|’)

.join combines the contents of an array into a string, separated by the value you passed it:

['this', 'is', 'some', 'text'].join('|');
// 'this|is|some|text'

.split is essentially the inverse of .join.

'this|is|some|text'.split('|');
// [ 'this', 'is', 'some', 'text' ]

Hi, this is actually related to this code here, where a string is split by multiple delimiters, sorry I should’ve made it more clear.

I just don’t know why they inserted ‘|’ into the join() function. Thank you

var separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?'];

var tokens = x.split(new RegExp(separators.join('|'), 'g'));
console.log(tokens);

This creates this equivalent regexp:

/ |\+|-|\(|\)|\*|\/|:|\?/g

In the context of regular expressions, a | character means you want to match either thing on both sides. Say you have this regexp:

/dog|cat/

It will match the "dog" in "crazy dog" or the "cat" in "crazy cat".

In the regexp that’s constructed in your code, it matches a space, a plus sign, a minus sign, etc. (globally, because of the g flag).

Now you feed this crazy regexp to the .split function, which tells it to split the x string whenever it matches these stuff.

1 Like