I was trying to implement a function in Node.js that does what the title of this question requires. For example, if the caracters was _
Input
foo_bar_baz
Output
foo_bar
Input
foo_bar_baz_foz
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
.
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, "_"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.