I was trying to split a string based on multiple delimiters by referring How split a string in jquery with multiple strings as separator
Since multiple delimiters I
I think you would need to escape the +, * and ?, since they've got special meaning in most regex languages
The following would be an easier way of accomplishing the same thing.
var tokens = x.split(new RegExp('[-+()*/:? ]', 'g'));
Note that -
must come first (or be escaped), otherwise it will think it is the range
operator (e.g. a-z
)
If you want to split based in multiple regexes and dont want to write a big regex
You could use replace
and split
.
Like this:
const spliters = [
/(\[products\])/g,
/(\[link\])/g,
/(\[llinks\])/g,
];
let newString = "aa [products] bb [link] [products] cc [llinks] dd";
spliters.forEach(regex => {
newString = newString.replace(regex, match => `æææ${match}æææ`);
});
const mySplit = newString.split(/æææ([^æ]+)æææ/)
console.log(mySplit);
This works very well for my case.
This is because characters like +
and *
have special meaning in Regex.
Change your join from |
to |\
and you should be fine, escaping the literals.
This should work:
var separators = [' ', '+', '(', ')', '*', '\\/', ':', '?', '-'];
var tokens = x.split(new RegExp('[' + separators.join('') + ']', 'g'));
Generated regex will be using regex character class: /[ +()*\/:?-]/g
This way you don't need to escape anything.
escape needed for regex related characters +,-,(,),*,?
var x = "adfds+fsdf-sdf";
var separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?'];
console.log(separators.join('|'));
var tokens = x.split(new RegExp(separators.join('|'), 'g'));
console.log(tokens);
http://jsfiddle.net/cpdjZ/