Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

javascript - Use RegExp to match a parenthetical number then increment it

I've been trying to find a way to match a number in a Javascript string that is surrounded by parenthesis at the end of the string, then increment it.

Say I have a string:

var name = "Item Name (4)";

I need a RegExp to match the (4) part, and then I need to increment the 4 then put it back into the string.

This is the regex I have so far:

([0-9]+)$

This regex does not work. Furthermore, I do not know how to extract the integer retrieved and put it back in the same location in the string.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The replace method can take a function as its second argument. It gets the match (including submatches) and returns the replacement string. Others have already mentioned that the parentheses need to be escaped.

"Item Name (4)".replace(/((d+))/, function(fullMatch, n) {
    return "(" + (Number(n) + 1) + ")";
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...