获取与lodash匹配模式的字符串结尾

时间:2016-11-10 05:46:29

标签: javascript regex lodash

如何在使用lodash之前获取字符串末尾的最后一个整数(包括破折号)?

'hello-world-bye-945'

所以最终结果只是-945

5 个答案:

答案 0 :(得分:1)

您可以使用 _.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"

答案 1 :(得分:1)

您可以使用String.prototype.lastIndexOf()String.prototype.slice()

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

答案 2 :(得分:0)

使用JavaScript String#match方法

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

尝试这种模式

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

[0-9A-z $&amp; +,:; =?@#|'&lt;&gt;。^ *()%!]匹配列表中的任何字符

“+”匹配无限时间

$断言字符串末尾的位置,或者在字符串末尾的行终止符之前(如果有的话)

相关问题