使用 javascript 替换特定的 html 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10816085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace particular html tags using javascript
提问by Sangram Nandkhile
I want to replace every <li>
tag with #
& every </li>
with <br />
我想替换每个<li>
与标签#
和每个</li>
与<br />
I think i need a Global repalce function for that rather than simple string.replace()
so..
我想我需要一个全局 repalce 函数,而不是简单的string.replace()
这样..
var s=obj1.innerHTML;
s = s.replace(/<li>/g,"# ");
s = s.replace(/</li>/g,"<br/>");
But it doesn't seem to be working. Any mistake ?
但它似乎不起作用。有什么错误吗?
EDIT:I am going to use the code in blogger & that is why it needs to be parsed.So that's why you see "
instead of "
.
编辑:我将使用博主中的代码 & 这就是为什么它需要被解析。所以这就是为什么你看到"
而不是"
.
回答by Siva Charan
回答by ziad-saab
obj1.innerHTML = obj1.innerHTML.replace(/<li>/g, '#').replace(/<\/li>/g, '<br>');
You just have to escape the /
in /li
otherwise it will be taken as a regex delimiter.
您只需要转义/
in/li
否则它将被视为正则表达式分隔符。
回答by paulofer85
Sorry but if the li
tag has some attribute (like style) you will have text that you don't want. For me the simplest way is using regular expressions like this:
抱歉,但如果li
标签具有某些属性(如样式),您将拥有不想要的文本。对我来说,最简单的方法是使用这样的正则表达式:
var regex = /(<li[^>]+>|<li>|<\/li>)/g;
s = s.replace(regex , ' ');
In the case you want to strip all the <tags> </tags>
(not only li tags) you should do something like this:
如果您想删除所有<tags> </tags>
(不仅是 li 标签),您应该执行以下操作:
var regex = /(<[^>]+>|<[^>]>|<\/[^>]>)/g;
s =s.replace(regex , ' ');
回答by Дамян Станчев
This works just fine:
这工作得很好:
<html>
<head>
<script type="text/javascript" src="http://streamed.in/static/js/jquery-1.4.1.min.js"></script>
<script>
$(document).ready(function(){
var s = $('#obj1').html();
s = s.replace(/<li>/g,'#');
s = s.replace(/<\/li>/g,'<br/>');
$('#obj1').html(s);
});
</script>
</head>
<body id="obj1">
<li>omg 1</li>
<li>omg 2</li>
<li>omg 3</li>
<li>omg 4</li>
</body>
</html>
or you can try and replace your second replace line with:
或者您可以尝试将第二个替换行替换为:
s.replace(/<\/li>/g,'<br/>');
回答by papaiatis
If you can use jQuery, this would help you:
如果您可以使用 jQuery,这将对您有所帮助:
$("li").after("#<br/>").remove();
$("li").after("#<br/>").remove();