Reputation: 1354
I need your help,
How can I get the last value (sub-string) of a text string that has hyphens in it?
var instr = "OTHER-REQUEST-ALPHA"
...some processing here to get the outstr value
var outstr = "ALPHA"
Upvotes: 2
Views: 932
Reputation: 115212
Use String#split
and Array#pop
methods.
var instr = "OTHER-REQUEST-ALPHA";
console.log(
instr.split('-').pop()
)
Or use String#lastIndexOf
and String#substr
methods
var instr = "OTHER-REQUEST-ALPHA";
console.log(
instr.substr(instr.lastIndexOf('-') + 1)
)
Or using String#match
method.
var instr = "OTHER-REQUEST-ALPHA";
console.log(
instr.match(/[^-]*$/)[0]
)
Upvotes: 3
Reputation: 3399
Use SPLIT and POP
"String - MONKEY".split('-').pop().trim(); // "MONKEY"
Or This
string2 = str.substring(str.lastIndexOf("-"))
Upvotes: 0
Reputation: 8921
The simplest approach is to simply split the string by your delimeter (ie. -
) and get the last segment:
var inString = "OTHER-REQUEST-ALPHA"
var outString = inString.split("-").slice(-1)[0]
That's it!
Upvotes: 0