Roy
Roy

Reputation: 3267

Create Regex from a string variable in javascript

var tags=["div","span","body"];
for (i=0; i<=tags.length; i++){
  source = source.replace(/\&lt\;<tags[i]/i, '<span class="tags[i]">&lt;tags[i]</span>');
}

Basically, I'm trying to put all the opening div,span and body tags around a span with a class set accordingly. But, I am having issues getting the variables inside there.

I can put lines and lines for each different tag but considering this function is called on every key press I want to keep the code as small and efficient as possible.

Or are there other alternatives? I mean it would be even better if something along these lines was possible:

source = source.replace(/\&lt\;<div|<span/i, '<span class="div|span">&lt;div|span</span>');

But, it clearly does not get me anywhere.

Upvotes: 1

Views: 216

Answers (2)

edi9999
edi9999

Reputation: 20554

You can use regexes with | (equivalent of OR): () are used to get the matched elements (div, span or body), and you can get them with $1

source.replace(/<(div|span|body)/i,'<span class="$1">&lt;$1&gt;</span>')

Upvotes: 1

freejosh
freejosh

Reputation: 11383

You can construct your regex from a string using the RegExp object:

source = source.replace(new RegExp("\\&lt\\;<" + tags[i], "i"), '<span class="' + tags[i] + '">&lt;' + tags[i] + '</span>');

But your idea for an alternative is also possible by capturing the tag and referencing it in the replacement:

source = source.replace(/\&lt\;<(div|span|body)/i, '<span class="$1">&lt;$1</span>');

Upvotes: 3

Related Questions