繁体   English   中英

从右到左删除特定字符之后的所有字符

[英]Remove all characters after specific character from right to left

我试图在 Node.js 中实现一个 function ,它可以满足这个问题的标题所要求的。 例如,如果字符是_

输入

foo_bar_baz

Output

foo_bar

输入

foo_bar_baz_foz

Output

foo_bar_baz

您可以使用string#substrstring#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);

如果你想使用正则表达式,你可以这样做.*(?=_)

 const string = "foo_bar_baz"; console.log(string.match(/.*(?=_)/)[0]);

您不需要正则表达式,只需按标识符拆分数据并从数组中删除最后一项并按标识符重新加入数组

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM