iLaYa  ツ
iLaYa ツ

Reputation: 4017

JS replace all the string before another specified character

I have the string

var str = "A > B > C > D > E";

expected output:

E

Means i want to remove/replace all the string upto last > symbol, or before > symbol from last.

Javascript replace will do the trick, but i don't know how to write the pattern for this.

or can we do this by split method?

Upvotes: 0

Views: 2181

Answers (3)

Danilo Valente
Danilo Valente

Reputation: 11342

Goran's solution is correct and beautiful (because of the regex). However, here's an alternative using String's .split method:

var str = "A > B > C > D > E";
var letters = str.split(' > '); 
var output = letters[letters.length - 1];

Upvotes: 2

Goran.it
Goran.it

Reputation: 6299

Using regex :

var str = "A > B > C > D > E";
var re = str.replace(/.*> /,"");

# print "E"

Upvotes: 4

Guffa
Guffa

Reputation: 700322

You can do it even simpler than using split or replace. Locate the last separator, and take the part of the string after that:

str = str.substr(str.lastIndexOf(' > ') + 3);

Demo: http://jsfiddle.net/Guffa/ahgB2/

Upvotes: 1

Related Questions