I have this regex, but it does not do what I expect:
name.replace(/sor\s*(\d )\.\s*szék/, function () {
return arguments[1] * 1 1;
});
My string is 1. sor 1. szék
. And I would expect a return 1. sor 2. szék
but the return value is: 1. 2
. Why?
CodePudding user response:
You get the value 1. 2
as the pattern sor\s*(\d )\.\s*szék
does not match the leading 1.
so that will be untouched.
The part arguments[1] * 1
is 1, and then you add 1 to it resulting in 2.
If you want to use replace, you can use 3 capture groups and use those in the replacement, passing the group parameters to the callback function of replace.
The captured digits are in group 2, and to prevent concatenating 2 strings you can add a
before group 2.
let name = "1. sor 1. szék";
name = name.replace(
/(sor\s*)(\d )(\.\s*szék)/,
(m, g1, g2, g3) => `${g1}${ g2 1}${g3}`
);
console.log(name);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You could simplify the regular experession and replace only the second occurence of digits with an incremented value.
const
string = '1. sor 1. szék.',
result = string.replace(/\d /g, (c => v => c-- ? v : v 1)(1));
console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>