Pawan
Pawan

Reputation: 32321

After some specified character extracting the value

I can have a Javascript variable as

'Ice Creams***Cone***Frosty';

OR

'Ice Creams***Cone'

I need to get the last value after ***

Means in first case i needed the value Frosty

and in second case , i needed the value Cone

Upvotes: 1

Views: 29

Answers (4)

Rajesh
Rajesh

Reputation: 3778

All the above methods will fail if *** is not found in the input string.

var delimiter = '***';
var str = 'Ice Creams***Cone***Frosty';
var strParts = str.split('***'); //returns an array
var numParts = strParts.length;
if(numParts > 0) {
   console.log(strParts[strParts.length - 1]);
} else {
   console.log('Delimiter ' + delimiter + ' not found in input string');
}

Upvotes: 0

Marcel Pfeiffer
Marcel Pfeiffer

Reputation: 1068

You can get the index of the last *** by using str.lastIndexOf('***').

For getting the last field you can use str.substring(index)

var seperator = '***'

// shifting index by seperator length
var i = str.lastIndexOf(seperator) + seperator.length;
var lastSubString = str.substring(i);

Upvotes: 0

dknaack
dknaack

Reputation: 60448

Just use the substr() and lastIndexOf() method

Sample

function extractEverythingAfter(value, seperator) {
   return value.substr(value.lastIndexOf(seperator) + seperator.length)
}

alert(extractEverythingAfter('Ice Creams***Cone***Frosty', '***'));
alert(extractEverythingAfter('Ice Creams***Cone', '***'));

Check out this JSFiddle Demo

More Information

Upvotes: 1

George
George

Reputation: 36784

You can split() your string on *** and then use .pop() to get the last element of the resulting array:

var str = 'Ice Creams***Cone***Frosty';
var last = str.split("***").pop();

JSFiddle

Upvotes: 2

Related Questions