Split a string based on multiple delimiters

前端 未结 6 2128
情深已故
情深已故 2020-11-29 06:12

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

相关标签:
6条回答
  • 2020-11-29 06:44

    I think you would need to escape the +, * and ?, since they've got special meaning in most regex languages

    0 讨论(0)
  • 2020-11-29 06:58

    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)

    0 讨论(0)
  • 2020-11-29 06:59

    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.

    0 讨论(0)
  • 2020-11-29 07:04

    This is because characters like + and * have special meaning in Regex.

    Change your join from | to |\ and you should be fine, escaping the literals.

    0 讨论(0)
  • 2020-11-29 07:07

    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.

    0 讨论(0)
  • 2020-11-29 07:08

    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/

    0 讨论(0)
提交回复
热议问题