humanbeing
humanbeing

Reputation: 1697

Alternative to regexp $1 for replace

I am trying to modify a substring with .replace() in javascript.

Basically I want to put arbitrary text before and after the match.

var pattern = new RegExp("<div"+"(.*?)>", "g");

var text = "<div><div class='someClass'>"

text = text.replace(pattern, "<pre>"+"<div>"+ "$1" + ">" +"</pre>")

The code above changes text to:

"<pre><div>></pre><pre><div> class='someClass'></pre>"

Besides the extra ">>" this is correct, but it is ugly in the replace function.

How can I change my regex so I

  1. Dont have to use $1 because it is not fully supported according to this

  2. How can I change replace to something simpler like

    text = text.replace(pattern, "<pre>"+ "THING_THAT_MATCHED" +"</pre>")
    

Upvotes: 1

Views: 822

Answers (1)

Kaspar Lee
Kaspar Lee

Reputation: 5596

Use the following code:

var pattern = new RegExp("<div"+"(.*?)>", "g");

var text = "<div><div class='someClass'>"

text = text.replace(pattern, function(match, first_match) {
    return "<pre>"+"<div>"+ first_match + ">" +"</pre>"
})

Also note that you code make your original code much neater, like so:

var pattern = new RegExp("<div"+"(.*?)>", "g");

var text = "<div><div class='someClass'>"

text = text.replace(pattern, "<pre><div>$1></pre>")

Upvotes: 2

Related Questions