1
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.

1

2 Answers 2

3

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>');
Sign up to request clarification or add additional context in comments.

1 Comment

Ah that works like a charm, I definately prefer the alternative. Thanks.
1

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>')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.