Split variable using a special character in JavaScript

后端 未结 4 878
夕颜
夕颜 2021-02-03 22:34

I have a variable var i = "my*text" I want to split it using special character *. I mean, I want to generate var one = "my&

4条回答
  •  攒了一身酷
    2021-02-03 23:15

    You can use the split method:

    var result = i.split('*');
    

    The variable result now contains an array with two items:

    result[0] : 'my'
    result[1] : 'text'
    

    You can also use string operations to locate the special character and get the strings before and after that:

    var index = i.indexOf('*');
    var one = i.substr(0, index);
    var two = i.substr(index + 1, i.length - index - 1);
    

提交回复
热议问题