1

I'm trying to take some parsed XML data, search it for instances of the tag and replace that tag (and anything that may be inside the font tag), and replace it with a simple tag.

This is how I've been doing my regexes:

var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; //Test against valid email
console.log('regex: ' + emailReg.test(testString));

and so I figured the font regex would be something like this:

var fontReg = /'<'+font+'[^><]*>|<.'+font+'[^><]*>','g'/;
console.log('regex: ' + fontReg.test(testString));

but that isn't working. Anyone know a way to do this? Or what I might be doing wrong in the code above?

1
  • I noticed you tagged your question with jquery. Is this XML in the DOM? Commented Sep 28, 2011 at 19:58

2 Answers 2

4

I think namuol's answer will serve you better then any RegExp-based solution, but I also think the RegExp deserves some explanation.


JavaScript doesn't allow for interpolation of variable values in RegExp literals.

The quotations become literal character matches and the addition operators become 1-or-more quantifiers. So, your current regex becomes capable of matching these:

# left of the pipe `|`
'<'font'>
'<''''fontttt'>

# right of the pipe `|`
<@'font'>','g'
<@''''fontttttt'>','g'

But, it will not match these:

<font>
</font>

To inject a variable value into a RegExp, you'll need to use the constructor and string concat:

var fontReg = new RegExp('<' + font + '[^><]*>|<.' + font + '[^><]*>', 'g');

On the other hand, if you meant for literal font, then you just needed:

var fontReg = /<font[^><]*>|<.font[^><]*>/g;

Also, each of those can be shortened by using .?, allowing the halves to be combined:

var fontReg = new RegExp('<.?' + font + '[^><]*>', 'g');
var fontReg = /<.?font[^><]*>/g;
Sign up to request clarification or add additional context in comments.

3 Comments

+1 nice answer. So replacing fonts with span would be something like: html = html.replace(/<(.?)font[^><]*>/g,'<$span>');
@David Almost. Just missing a 1 in the replace: '<$1span>'. But, with that it should work.
Fantastic answer, very thorough.
4

If I understand your problem correctly, this should replace all font tags with simple span tags using jQuery:

$('font').replaceWith(function () {
    return $('<span>').append($(this).contents());
});

Here's a working fiddle: http://jsfiddle.net/RhLmk/2/

1 Comment

+1 way way better than trying to hack at HTML source using crude regex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.