Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace every number in a string with a different number? [duplicate]

Possible Duplicate:
How to increase each number in a string?

In JavaScript how could I replace every number in a string with that number + 20?

So, this string: "min: 300px and max: 600px, min: 800px"

Would end up as "min: 320px and max: 620px, min: 820px"

like image 654
Matt Stow Avatar asked Jan 12 '13 01:01

Matt Stow


People also ask

How do I replace a number in a string?

To replace all numbers in a string, call the replace() method, passing it a regular expression that globally matches all numbers as the first parameter and the replacement string as the second. The replace method will return a new string with all matches replaced by the provided replacement. Copied!

How do you replace every instance of a character in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

How replace all occurrences of a string in TypeScript?

To replace all occurrences of a string in TypeScript, use the replace() method, passing it a regular expression with the g (global search) flag. For example, str. replace(/old/g, 'new') returns a new string where all occurrences of old are replaced with new .


1 Answers

Maybe the shortest version:

"min: 300px and max: 600px, min: 800px".replace(/\d+/g, function(c) {
    return parseInt(c, 10) + 20;
});
like image 105
VisioN Avatar answered Nov 14 '22 21:11

VisioN