Home > Enterprise >  string replace with return statement gives different result. need the clarity
string replace with return statement gives different result. need the clarity

Time:11-02

Case 1 : replace with function return results j<*zz

const str = 'z<*zj';
const letters = Array.from(str.replace(/[^a-zA-Z]/gm, ''));

const result = str.replace(/[a-zA-Z]/gm, () => letters.pop());
console.log('result', result); // result => j<*zz/

Case 2 : replace without function return results j<*jj

const str = 'z<*zj';
const letters = Array.from(str.replace(/[^a-zA-Z]/gm, ''));

const result = str.replace(/[a-zA-Z]/gm,  letters.pop());
console.log('result', result); // result => j<*jj/

So, It differs with function integration. what is behind ? Need the help to understand.

CodePudding user response:

As per the documentation, If a replacement parameter is a function, it will be invoked for every match and its return value is used as the replacement text.

Hence, In case 1 as we are passing replacement as an arrow function, it executes for each match and replace with the letters array last element. As we are using Array.pop() method, It changes the length of the original array and returns the last element.

For example,

const str = 'z<*zj';

const letters = Array.from(str.replace(/[^a-zA-Z]/gm, ''));

console.log(letters.pop()); // j

console.log(letters); // ["z", "z"]

In this case, in second iteration it will pop the z and replaced with the matched value.

Now if we will talk about the case 2, As replacement parameter is a string, It will replace the substring matched by pattern in a single go.

For example,

const str = 'z<*zj';

const arr = ['z', 'z', 'j'];

const result = str.replace(/[a-zA-Z]/g, arr.pop());

console.log(result);

CodePudding user response:

There exists an overload for String.prototype.replace that accepts a function. This function will execute on every match. Each match then mutates letters via the pop method.

When you use letters.pop() instead of a method that returns letters.pop(), it is only executed once and its result is reused for each match.

Since the last letter in letters is j, letters.pop() evaulates to j and each letter is replaced with j.

When using the function variant, the last letter is j, so the first letter is replaced with j, but for subsequent matches, we're now popping from a mutated array, so we then return z and finally z.

  • Related