Alex Rivera | Logout

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

Asked 2011-09-17T17:26:44.680
12

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?

Edit
Report

1 Answer

12

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);
//-> "==~~~~~=="
answered 2011-09-17T17:29:35.027

Your Answer