+ 2

Javascript> Is it possible change number in string?

I want change "A240 B255 C138 D333 E290" to "A250 B245 C148 D323 E300" (if number is odd -> plus 10, if it is even -> minus 10) How can I make it without loop?

29th Jun 2017, 2:10 AM
Daniel Simson
Daniel Simson - avatar
1 Antwort
+ 6
You should use regular expression (untested) var str = 'A240 B255 C138 D333 E290'; var res = str.replace(/\d+/g, function(n) { return +n + [10, -10][n & 1]; }); console.log('string: ' + str + '\n\nresult: ' + res); //or if your browser support es6 syntax use this. // ES6 let str = 'A240 B255 C138 D333 E290'; let res = str.replace(/\d+/g, n => +n + [10, -10][n & 1]); console.log(`string: ${str}\n\nresult: ${res}`);
29th Jun 2017, 2:24 AM
김정제(Legacy)
김정제(Legacy) - avatar