使用Regex删除Javascript中的HTML标记 [英] Remove HTML Tags in Javascript with Regex

查看:110
本文介绍了使用Regex删除Javascript中的HTML标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Javascript中删除字符串中的所有html标记。
继承人我拥有的......我无法弄清楚为什么它不起作用....任何人都知道我做错了什么?

I am trying to remove all the html tags out of a string in Javascript. Heres what I have... I can't figure out why its not working....any know what I am doing wrong?

<script type="text/javascript">

var regex = "/<(.|\n)*?>/";
var body = "<p>test</p>";
var result = body.replace(regex, "");
alert(result);

</script>

非常感谢!

推荐答案

试试这个,注意HTML的语法太复杂了,正规表达式在100%的时间都不正确:

Try this, noting that the grammar of HTML is too complex for regular expressions to be correct 100% of the time:

var regex = /(<([^>]+)>)/ig
,   body = "<p>test</p>"
,   result = body.replace(regex, "");

console.log(result);

如果你愿意使用像 jQuery ,你可以这样做:

If you're willing to use a library such as jQuery, you could simply do this:

console.log($('<p>test</p>').text());

这篇关于使用Regex删除Javascript中的HTML标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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