How split a string in jquery with multiple strings as separator

后端 未结 2 2019
感动是毒
感动是毒 2020-12-19 15:21

i want to split a string in jquery or javascript with multiple separator.
for one string as separator we can have :

var x = \"Name: John Doe\\nAge: 30\         


        
2条回答
  •  余生分开走
    2020-12-19 15:44

    You can do

    var tokens = x.split(/Age:|Date:/g);
    

    This gives 3 strings :

    ["Name: John Doe
    ", " 30
    Birth ", " 12/12/1981"]
    

    If you want also to get the separators, use

    var tokens = x.split(/(Age:|Date:)/g);
    

    This gives 5 strings :

    ["Name: John Doe
    ", "Age:", " 30
    Birth ", "Date:", " 12/12/1981"]
    

    If you want to build your regexp dynamically use

    var separators = ["Date:", "Age:"];
    var tokens = x.split(new RegExp(separators.join('|'), 'g'));​​​​​​​​​​​​​​​​​
    

    or

    var separators = ["Date:", "Age:"];
    var tokens = x.split(new RegExp('('+separators.join('|')+')', 'g'));
    

提交回复
热议问题