BobbyJones
BobbyJones

Reputation: 1354

Getting the last substring value of a string with hyphens in it

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

Answers (3)

Pranav C Balan
Pranav C Balan

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

Neo
Neo

Reputation: 3399

Use SPLIT and POP

"String - MONKEY".split('-').pop().trim(); // "MONKEY"

Or This

string2 = str.substring(str.lastIndexOf("-"))

Upvotes: 0

AP.
AP.

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

Related Questions