Neel
Neel

Reputation: 547

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.

Upvotes: 8

Views: 35680

Answers (2)

Adil
Adil

Reputation: 148110

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());

Upvotes: 18

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Just use plain 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];

Upvotes: 5

Related Questions