开发者

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?


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;


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜