Extract part of the string

后端 未结 2 553

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:27

    Just split the string on the separator and pop of the last part :

    var lastPart = str.split(separator).pop();
    

    FIDDLE

    0 讨论(0)
  • 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];
    
    0 讨论(0)
提交回复
热议问题