Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string and get last match in jQuery?

I have string like this

This is ~test content ~ok ~fine.

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

like image 834
Neel Avatar asked Dec 06 '12 05:12

Neel


1 Answers

You can use 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 the string to array and get the element at last index, last index is length of array - 1 as array is zero based index.

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

OR, simply call pop on array got after split

str = "~test content ~thanks ok ~fine";    
console.log(str.split('~').pop());
like image 98
Adil Avatar answered Oct 19 '22 11:10

Adil