Extract part of the string

后端 未结 2 550

I need to extract part of the string while looks like this for example:

01.   Artist Name - Song Title

So I have

2条回答
  •  伪装坚强ぢ
    2021-01-16 23:35

    You could try to use String.split, but I'd suggest using String.indexOf and String.substring to find the first offset of your separator and then select the rest of the string. Using String.split could fail if your name and song title contains the separator internally.

    You could also write a regex to split the arguments, which would let you extract the artist and song title separately.

    To use indexOf:

    var str = "01.   Artist Name - Song Title";
    var sep = "   "
    var artist_title = str.substring(str.indexOf(sep) + sep.length);
    document.getElementById("demo").innerHTML = artist_title;
    

    To use a regex:

    var str = "01.   Artist Name - Song Title";
    var regex = /(\d+)\.   ([^-]+) - (.*)/
    var matches = str.match(regex);
    document.getElementById("demo").innerHTML = matches[2] + " : " + matches[3];
    

提交回复
热议问题