将文本与锚定标记分离的Javascript
在javascript中使用正则表达式泛化字符串时,我面临着困难。 我有一个字符串,其中包含两个锚定标记,其中包含的文本可以是以下内容:将文本与锚定标记分离的Javascript,javascript,regex,tags,anchor,Javascript,Regex,Tags,Anchor,在javascript中使用正则表达式泛化字符串时,我面临着困难。 我有一个字符串,其中包含两个锚定标记,其中包含的文本可以是以下内容: <b> text <a href="javascript:opendynamicurlwindow('http://www.google.com', '', '', '', '','no')">www.google.com< /a ><abc><a href="javascript:opendynamicu
<b> text <a href="javascript:opendynamicurlwindow('http://www.google.com', '', '', '', '','no')">www.google.com< /a ><abc><a href="javascript:opendynamicurlwindow( 'http://www.flipkart.com', '', '', '', '','no')" >www.flipkart.com</a></b>
文本
我需要将此文本转换为html兼容的值,锚定标记除外,即
1. <b> text should be encoded as <b> text
2. <abc> should be encoded as <abc> text
3. </a> should be encoded as </a> text
1。文本应编码为b文本
2.应编码为abc文本
3.应编码为/a文本
我在分离文本和锚定标记以正确处理它们时遇到困难。
我已经尝试过正则表达式:(]>+),但是匹配对多个URL不起作用。到js端
htmlencode
的一个棘手方法是:
var html = '<h1>Your <a href="http://google.com">html</a></h1>';
$('<div />').text(html).html()
var html='Your';
$('').text(html).html()
另一种方式是直接替换:
html
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
html
.替换(/&/g,“&;”)
.replace(//g,“”)
.替换(/“/g,”)
.替换(/'/g,';);
如果要正确解析html文本,应使用DOM解析器。但在您的情况下,may可以工作,下面是简单的代码:
var anchorreg = /<a\s+[^>]+>(.*?)<\/a>/g;
var links = s.match(anchorreg);
var res = s.replace(anchorreg, '#anchor#');
res = htmlencode(res); // where htmlencode is one of methods above
for(var i=0;i<links.length;i++) res = res.replace('#anchor#', links[i])
console.log(res);
var-anchorreg=/]+>(.*)/g;
var links=s.match(anchorreg);
var res=s.替换(锚定器,锚定器);
res=htmlencode(res);//其中htmlencode是上述方法之一
对于(var i=0;iIsn不是这样:$('').text('http://www.google.com
www.google。comhttp://www.flipkart.comwww.flipkart.com“”.html()
起作用?为什么要保存未编码的URL?这是一个注释字段。因此,我必须保持链接的原样,并在保存之前显示文本以供确认。我在答案中添加了代码