Javascript RegEx替换不在HTML标签内的所有字符 [英] Javascript RegEx replace all characters not within HTML tags

查看:88
本文介绍了Javascript RegEx替换不在HTML标签内的所有字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一些帮助,我的正则表达式有点生疏......



我试图用JavaScript代替HTML中的所有字符字符。



例如用短划线 - 替换这些字符,

 < div class =test> Lorem Ipsum< br /> Dolor Sit Amet< / div> 

会被替换为:

 < div class =test> ------------< br /> -------------- < / DIV> 

所以我在寻找

  str.replace(/ YourMagicalRegEx / g,' - '); 

请帮忙,我得到了如何使用正则表达式,HTML标签内的文本正则表达式,但所有不在html标签内的字符似乎相当棘手......!

额外挑战:必须与IE7兼容。


<使用jQuery:

  html ='< div class =test> Lorem Ipsum< br /> Dolor Sit Amet< / div>'; 
node = $(< div>+ html +< / div>);
node.find('*')。contents()。each(function(){
if(this.nodeType == 3)
this.nodeValue = Array(this.nodeValue。长度).join(' - ')

});
console.log(node.html())

(我没有IE7

如果你喜欢正则表达式,它就像这样:



$ p $ lt; code> html = html.replace(/< [<>] +> | ./g,function($ 0){
return $ 0 [0] = ='<'?$ 0:' - ';
});

基本上,我们用自己和超出标签的字符替换为破折号。


Looking for a bit of help, my regex is a bit rusty...

I'm trying to replace all characters not within HTML tags in javascript by a character.

For example replace those characters by a dash "-",

<div class="test">Lorem Ipsum <br/> Dolor Sit Amet</div>

Would be replaced by:

<div class="test">------------<br/>--------------</div>

So I'm looking for

str.replace(/YourMagicalRegEx/g, '-');

Please help, I get how to return text not within html tags with regex, text within html tags with regex, but all characters not within html tags seems quite tricky...!

Additional Challenge: Must be IE7 and up compatible.

解决方案

Using jQuery:

html = '<div class="test">Lorem Ipsum <br/> Dolor Sit Amet</div>';
node = $("<div>" + html + "</div>");
node.find('*').contents().each(function() {
    if(this.nodeType == 3)
        this.nodeValue = Array(this.nodeValue.length).join('-')

});
console.log(node.html())

(I don't have IE7 at hand, let me know if this works).

If you prefer regular expressions, it goes like this:

html = html.replace(/<[^<>]+>|./g, function($0) {
    return $0[0] == '<' ? $0 : '-';
});

Basically, we replace tags with themselves and out-of-tags characters with dashes.

这篇关于Javascript RegEx替换不在HTML标签内的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆