Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Increment a number in a string in with regex

I get the name of an input element, which is a string with a number (url1). I want to increment the number by 1 (url2) in the easiest and quickest way possible.

My way would be to get d / restofstring, ++ the match, then put together number with restofstring. Is there a better way?

Update:

My final (dummy)code became:

var liNew = document.createElement('li'); 
liNew.innerHTML = liOld.innerHTML; 
var els = Y.Dom.getChildrenBy(liNew, function(el) { 
    return el.name.match(/d+$/); 
} // YUI method where the function is a test 
for (var i = 0, el; el = els[i]; i++) { 
    el.name = el.name.replace(/d+$/, function(n) { return ++n }); 
} 
list.appendChild(liNew); 
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

How about:

'url1'.replace(/d+$/, function(n){ return ++n }); // "url2"
'url54'.replace(/d+$/, function(n){ return ++n }); // "url55"

There we search for a number at the end of the string, cast it to Number, increment it by 1, and place it back in the string. I think that's the same algo you worded in your question even.

Reference:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...