![](/img/trans.png)
[英]Update HTML to have closing tags with JavaScript or jQuery
[英]JavaScript/jQuery: Insert space after special characters and closing html tags
我有以下字符串:
<h1 class="title">This is some heading?</h1><h2 class="desc">Here is the description for it.</h2>
想要使其看起来像:
<h1 class="title">This is some heading? </h1> <h2 class="desc">Here is the description for it.</h2>
以上分为两部分:
对于1,我尝试了以下方法:
str = str.replace(/\?/g,'? ');
上面是否在后面插入空格? 但是它很死板。 我不能对所有特殊字符应用相同的规则。 那怎么办呢?
对于2,我尝试了以下方法:
//To entirely remove all opening html tags
str = str.replace(/<.*?>/g, '');
//To replace closing tag with space
str = str.replace(/<\/.*?>/g, ' ');
上面代码的问题是后面的部分工作正常。 第一部分,即删除所有打开的html标签的代码也影响关闭的html标签,这是不希望的。 那么如何修改上面的代码,以便删除诸如<h1>, <div>,
等开头的标签?
比赛 :
\s*(?<ws>[<>])\s*
并替换为
$1
对于第一个问题,您可以使用:
s.replace(/([?%])/g, '$1 ') //you could put more characters within `[..]`
对于打开标签问题,您可以使用:
str.replace(/<[^/].*?>/g, '')
基本上, [abcdef]
表示它是a,b,c,d,e,f中任何一个的占位符。 %
和?
类似?
。 将^
放在类(方括号)中意味着它是除^
其他字符的占位符。 因此<[^/]
将不接受</
字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.