[英]Remove all characters after specific character from right to left
I was trying to implement a function in Node.js that does what the title of this question requires.我试图在 Node.js 中实现一个 function ,它可以满足这个问题的标题所要求的。 For example, if the caracters was _
例如,如果字符是_
Input输入
foo_bar_baz
Output Output
foo_bar
Input输入
foo_bar_baz_foz
Output Output
foo_bar_baz
You can use string#substr
with string#lastIndexOf
to remove pick letter between first character till last occurrence of your char
.您可以使用
string#substr
和string#lastIndexOf
来删除第一个字符之间的选择字母,直到最后一次出现char
。
word.substr(0, word.lastIndexOf(char))
const str = ['foo_bar_baz', 'foo_bar_baz_foz'], char = '_', result = str.map(word => word.substr(0, word.lastIndexOf(char))); console.log(result);
If you want to use regex, you can just do .*(?=_)
如果你想使用正则表达式,你可以这样做
.*(?=_)
const string = "foo_bar_baz"; console.log(string.match(/.*(?=_)/)[0]);
You don't need regex for this, just split the data by the identifier and remove the last item from the array and rejoin the array by the identifier您不需要正则表达式,只需按标识符拆分数据并从数组中删除最后一项并按标识符重新加入数组
const test = "foo_bar_baz_foz"; function removeLR(string, identifier) { const arr = string.split(identifier); arr.splice(arr.length - 1, 1); return arr.join(identifier); } console.log(removeLR(test, "_"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.