[英]How to use regular expression to add plus 1 in the middle of a string
我有name_1
,可以輕松地做一個正則表達式使name_2
name_3
。
我的問題是,現在我有了name_1'english
和name_1'portuguese
。
這是我的代碼:
the_string.replace(/_\d+$/, '_'+(1))
當然,這對於第一個需求非常有效,但現在我不能。 我該如何實現?
使用帶有replace
的回調:
the_string = the_string.replace(/_(\d+)/, function(m, c0) {
return "_" + (+c0 + 1);
});
在那里,我為匹配的數字使用捕獲組,該捕獲組作為第二個參數傳遞給函數,因此我將返回的數字轉換為一個數字加一個(在其前面帶有_
)。
例:
var the_string = "name_1'en"; the_string = the_string.replace(/_(\\d+)/, function(m, c0) { return "_" + (+c0 + 1); }); snippet.log(the_string);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.