Jump to content

Dynamically creating a regular expression


Fmdpa

Recommended Posts

I'm stumped on how to create a regex dynamically. I can't use "+" to concatenate a variable onto the regex because "+" is a metacharacter within a regex. And, to my knowledge, I can't terminate a regex like you can with a string by closing a quote. Is it possible?

Link to comment
Share on other sites

Now I've got another problem with the JS replace() function. I want to replace the matched text (with the regex in the first arg) with the text surrounded by a set of tags. e.g.

regex = new RegExp('(' + whitelist.join('|') + ')', 'ig');thisNode.nodeValue = thisNode.nodeValue.replace(regex, function(replaced) {														   '<b>' + replaced + '</b>'														 });

Of course, this replaces doesn't actually create an element node. How could I do that?

Link to comment
Share on other sites

Is there a way to surround matched text with tags? If I create the element, I don't know where to append it unless I get the position of the match (in the .replace() call).

Link to comment
Share on other sites

JSYK, I'm using this only for a new browser so I don't have to worry about old JS incompatibility issues. I know you are quite familiar with JS methods so if you know of one that might do what I'm needing to do (even if it isn't supported in older browsers), I would love to hear about it. I'm beginning to think the solution might not even include the replace() method...

Link to comment
Share on other sites

Try this:

function func () {	var el = document.getElementById("myElement");	var myClone = el.cloneNode(true);	var b = document.createElement('b');	b.appendChild(myClone);	el.parentNode.replaceChild(b, el);}

Link to comment
Share on other sites

I think there was a misunderstanding (not that I don't appreciate your help!). Here's what I want to do:

"<b>the <i>text</i> value of this b element node</b>" // search for 'value' with the regex [b]/value/i[/b]. If it is found, wrap it in <u> tags =>"<b>the <i>text</i> <u>value</u> of this b element node</b>"

I have a feeling the solution may utilize the search(), substr(), match(), cloneNode(), replaceChild(), createElement(), createTextNode() methods and possibly others.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...