gpt4 book ai didi

javascript - 使用指定的分隔符分割字符串,并替换某些部分

转载 作者:行者123 更新时间:2023-11-28 16:03:08 25 4
gpt4 key购买 nike

我有这样的内容Go to {#www.google.com##Google#} ,我想将其用作可点击的链接,如下所示:

Go to <a href="www.google.com" title="Google">Google</a> .

我的尝试:var splCharData = splCharData.split(/[\{#\#}]/g);

最佳答案

查找正则表达式实际上是最简单的部分。人们很容易忘记,即使在 JavaScript 中,您也应该防范 XSS 漏洞。

确保值正确转义的一种方法是实际创建一个 anchor ,然后查询其 outerHTML 属性:

var str = 'Go to {#www.google.com##Google#}',
m = /\{#([^#]+)##([^#]+)#\}/g;

alert(str.replace(m, function($0, $1, $2) {
var a = document.createElement('a');
a.href = 'http://' + $1;
a.title = $2;
a.textContent = $2;

return a.outerHTML;
}));

Demo

或者,您可以使用仅字符串方法并手动转义您插入属性内的任何内容。

var str = 'Go to {#www.google.com##Google#}',
m = /\{#([^#]+)##([^#]+)#\}/g,
htmlspecialchars = function(str) {
return str
.replace('<', '&lt;')
.replace('&', '&amp;')
.replace('>', '&gt;')
.replace('"', '&quot;');
};

alert(str.replace(m, function($0, $1, $2) {
return '<a href="' +
htmlspecialchars('http://' + $1) +
'" title="' +
htmlspecialchars($2) +
'">' +
htmlspecialchars($2) +
'</a>';
}));

Demo

关于javascript - 使用指定的分隔符分割字符串,并替换某些部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16207311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com