簡體   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