Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 757
Jacob Rask Avatar asked Nov 16 '09 15:11

Jacob Rask


People also ask

How do you add numbers in regex?

For each step add the regex (without delimiters), the modifiers and the substitution string. For the above example this would be (6 + 1 + 3) + (3 + 0 + 2) + (2 + 1 + 0) = 18 .

Can you use regex for numbers?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9].

What does $1 do in regex?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What does the plus character [+] do in regex?

Inside a character class, the + char is treated as a literal char, in every regex flavor. [+] always matches a single + literal char. E.g. in c#, Regex. Replace("1+2=3", @"[+]", "-") will result in 1-2=3 .


1 Answers

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:

  • String.prototype.replace - can take a regex
like image 187
Roatin Marth Avatar answered Sep 19 '22 19:09

Roatin Marth