calebo
calebo

Reputation: 3442

Get end of string that matches pattern with lodash

How can I get the last integer(s) at the end of the string including the dash before it using lodash?

'hello-world-bye-945'

So the end result is just -945.

Upvotes: 0

Views: 1839

Answers (5)

Chel
Chel

Reputation: 11

Try this pattern

-[0-9A-z$&+,:;=?@#|'<>.^*()%!]+$

[0-9A-z$&+,:;=?@#|'<>.^*()%!] match any character in the list

"+" match unlimited time

$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

Upvotes: 0

choz
choz

Reputation: 17878

You can use _.words.

E.g

var str1 = 'hello-world-bye-945';
var str2 = 'hello-world-bye';
var pattern = /-(\d+)$/;

_.words(str1, pattern)[0]
// Returns "-945"

_.words(str2, pattern)[0]
// Returns "undefined"

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can use String.prototype.lastIndexOf(), String.prototype.slice()

var str = "hello-world-bye-945";
var match = str.slice(str.lastIndexOf("-"));
console.log(match);

Upvotes: 1

Mahi
Mahi

Reputation: 1727

s = 'hello-world-bye-945'.split('-');
ans="-"+s[s.length-1]
console.log(ans);

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115242

Use JavaScript String#match method

console.log(
  'hello-world-bye-945'.match(/-\d+$/)[0]
)

Upvotes: 0

Related Questions