How to split a string and get the latest match in jQuery?

I have a line like this

This is ~test content ~ok ~fine.

I want to get "fine" , which is after the special character ~ and at the last position in the string using jQuery.

+8
jquery split match
source share
2 answers

You can use a combination of [substring ()] [1] and [lastIndexOf ()] [2] to get the last element.

 str = "~test content ~thanks ok ~fine"; strFine =str.substring(str.lastIndexOf('~')); console.log(strFine ); 

You can use [ split () ] [4] to convert a string to an array and get the element at the last index, the last index of length of array - 1 , since the array is an index based on zero.

 str = "~test content ~thanks ok ~fine"; arr = str.split('~'); strFile = arr[arr.length-1]; console.log(strFile ); 

OR, just call pop in the array obtained after split

 str = "~test content ~thanks ok ~fine"; console.log(str.split('~').pop()); 
+14
source share

Just use regular JavaScript:

 var str = "This is ~test content ~thanks ok ~fine"; var parts = str.split("~"); var what_you_want = parts.pop(); // or, non-destructive: var what_you_want = parts[parts.length-1]; 
+5
source share

All Articles