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);
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 .
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].
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
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 .
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 regexIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With