Toniq
Toniq

Reputation: 5016

Extract part of the string

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

01.   Artist Name - Song Title

So I have counter at the beginning, dot and a separator can be anything, currenty separator is:

var separator =    

I want to extract everything after separator.

Using jquery/javascript.

Upvotes: 2

Views: 12167

Answers (2)

E. Anderson
E. Anderson

Reputation: 3493

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];

Upvotes: 1

adeneo
adeneo

Reputation: 318342

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

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

FIDDLE

Upvotes: 11

Related Questions