0

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

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

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

4

2 回答 2

3

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

确保值被正确转义的一种方法是实际创建一个锚点,然后查询它的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;
}));

演示

或者,您可以使用纯字符串方法并手动转义您在属性中推送的任何内容。

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>';
}));

演示

于 2013-04-25T06:08:12.473 回答
1

查找:\{#([^#]+)##([^#]+)#\}

用。。。来代替 :<a href="$1" title="$2">$2</a>

于 2013-04-25T05:58:07.947 回答