Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex- replace sequence of characters with same number of another character

I'm trying to replace part of a string with the same number of dummy characters in JavaScript, for example: '==Hello==' with '==~~~~~=='.

This question has been answered using Perl and PHP, but I can't get it to work in JavaScript. I've been trying this:

txt=txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3");

The pattern match works fine, but the replacement does not - the second part adds '~~' instead of the length of the pattern match. Putting the "$2" inside the parentheses doesn't work. What can I do to make it insert the right number of characters?

like image 869
hamboy Avatar asked Sep 17 '11 17:09

hamboy


2 Answers

Use a function for replacement instead:

var txt = "==Hello==";
txt = txt.replace(/(==)([^=]+)(==)/g, function ($0, $1, $2, $3) {
    return $1 + (new Array($2.length + 1).join("~")) + $3;
});

alert(txt);
//-> "==~~~~~=="
like image 200
Andy E Avatar answered Oct 11 '22 12:10

Andy E


The issue with the expression

txt.replace(/(==)([^=]+)(==)/g, "$1"+Array("$2".length + 1).join('~')+"$3") 

is that "$2".length forces $2 to be taken as a string literal, namely the string "$2", that has length 2.

From the MDN docs:

Because we want to further transform the result of the match before the final substitution is made, we must use a function.

This forces evaluation of the match before the transformation.

With an inline function as parameter (and repeat) -- here $1, $2, $3 are local variables:

txt.replace(/(==)([^=]+)(==)/g, (_,$1,$2,$3) => $1+'~'.repeat($2.length)+$3);

txt = '==Hello==';

//inline function
console.log(
  txt.replace(/(==)([^=]+)(==)/g, (_, g1, g2, g3) => g1 + '~'.repeat(g2.length) + g3)
);
like image 30
user2314737 Avatar answered Oct 11 '22 12:10

user2314737