Reputation: 3267
var tags=["div","span","body"];
for (i=0; i<=tags.length; i++){
source = source.replace(/\<\;<tags[i]/i, '<span class="tags[i]"><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(/\<\;<div|<span/i, '<span class="div|span"><div|span</span>');
But, it clearly does not get me anywhere.
Upvotes: 1
Views: 216
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"><$1></span>')
Upvotes: 1
Reputation: 11383
You can construct your regex from a string using the RegExp object:
source = source.replace(new RegExp("\\<\\;<" + tags[i], "i"), '<span class="' + tags[i] + '"><' + 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(/\<\;<(div|span|body)/i, '<span class="$1"><$1</span>');
Upvotes: 3