t = "(10px,10px)"
t = t.replace(/-|\d+/g,3,5)
I wanted it to result in (3px, 5px)
Where is the error?
t = "(10px,10px)"
t = t.replace(/-|\d+/g,3,5)
I wanted it to result in (3px, 5px)
Where is the error?
@dvd already explained the reason .
Replace only accepts 2 parameters:
replace(string_buscada, nova_string);
My contribution is in the method of doing this, which would be using a callback instead of replace , like this:
var t = "(10px,10px)"
var change = [3,5];
var def = 10;
t = t.replace(/-|\d+/g,function(m){
return change.length?change.shift():def;
});
console.log(t);
The callback will change the catch found by the value passed in return
, as I'm passing shift
from var change
will remove the first value from it and return to substitution and so on for each match found.
The var def
is for case change
is empty and has matchs
to be replaced.
The regex for negative numbers is indeed wrong. I suggest using:
/[+-]?\d+/g
The replace
only accepts 2 parameters:
replace(string_buscada, nova_string);
Soon your code will not work this way. One suggestion is to use match
and make 2 replaces
with the indexes of the regex result:
t = "(10px,10px)";
// ↑↑ ↑↑
// m[0] m[1]
m = t.match(/[-|\d]+/g);
t = t.replace(m[0],3).replace(m[1],5);
console.log(t);
Another example with different values:
t = "(4px,2px)";
m = t.match(/[-|\d]+/g);
t = t.replace(m[0],3).replace(m[1],5);
console.log(t);
As raised by the friend wmsouza , this regex is not correct. If one of the numbers were negative, it would replace only the negative sign, not the whole number.
The correct regex would be:
/[-|\d]+/g
Example:
t = "(4px,-2px)";
m = t.match(/[-|\d]+/g);
t = t.replace(m[0],3).replace(m[1],5);
console.log(t);
Replace
has only 2 arguments. The second argument of Replace
is not an array array parameter. In Replace
you should put an expression representing the replacement of all parts of the regular expression in the second argument. You set up the groups you want to capture in your regular expression and use the expression $n
where n
is the number of the captured group.
Example below:
var t = "(10px,10px)";
var n = ["3", "5"];
var r = t.replace(/(\()\d+(px,)\d+(px\))/g, "$1"+n[0]+"$2"+n[1]+"$3");
console.log(t);
console.log(r);