简体   繁体   中英

jquery / javascript: regex to replace instances of an html tag

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?

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/

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM