简体   繁体   English

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

[英]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#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);

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.

相关问题 删除多行textarea中特定字符后的所有字符 - Remove all characters on line after a specific character in multiline textarea 删除字符串中出现在特定字符之后的字符 - Remove characters in String that appear after specific character 从字符串中过滤掉特定字符。 如果它出现在某些字符的左侧,则只想将其删除 - Filter out a specific character from string. Only want to remove it if it appears to the left of certain characters RegEx-在特定字符(#)之后获取所有字符 - RegEx - Get All Characters After A Specific Character (#) 如何删除数组数据中特定字符之前的所有字符 - How to remove all characters before specific character in array data 从左到右替换所有字符的最佳方法? - Best way to replace all characters from left to right? "删除最后一个特殊字符 javascript 之后的所有字符" - Remove all characters after the last special character javascript 删除第5个字符之后的字符串的所有字符? - remove all characters of a string after 5th character? 如何左右移动字符串的字符,每当出现特定字符时计数? - How to move left and right through characters of a string, counting whenever a specific character appear? 如何从作为参数的字符串中删除所有特殊字符? - How to remove all special characters from the character string that comes as a parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM