我有一个html页面,现在我正在显示一个字符串,其中包含以' @'开头的文字。我需要做的是替换以' @'开头的字符串中的所有文本。使用javascript之类的锚标签
例如:
我的字符串:
在沙滩上与@ sarah333和@ kevin0955玩得很开心。
必填项:
had a great time with <a href="http://example.com/sarah333">@sarah333</a> and <a href="http://example.com/kevin9099">@kevin9099</a> at beach.
答案 0 :(得分:3)
试试这个
str = 'had a great time with @sarah333 and @kevin0955 at beach.';
replacedStr = str.replace(/\s\@(.*?)(\s|$)/g, ' <a href="http://example.com/$1">@$1</a>$2');
答案 1 :(得分:1)
又一种方式
document.getElementById('r').innerHTML = 'Result: ' +
'had a great time with @sarah333 and @kevin0955 at beach.'.replace(/@(\w+)/g, '<a href="http://example.com/$1">@$1</a>');
&#13;
<div id='s'>Source: had a great time with @sarah333 and @kevin0955 at beach.</div>
<div id='r'></div>
&#13;
答案 2 :(得分:0)
在Php中
$str = "had a great time with @sarah333 and @kevin0955 at beach";
$str = preg_replace('/\B\@([a-zA-Z0-9_]{1,})/', '<a href="http://example.com/$1" class="primary-black">$0</a>', html_entity_decode($str));
echo $str;
在Javascript中
var str = "had a great time with @sarah333 and @kevin0955 at beach";
str = str.replace(/@(\w*[a-zA-Z_]+\w*)/gim, '<a class="primary-black" href="http://www.google.com/$1">$1</a>');
答案 3 :(得分:-2)
<html>
<head>
<script>
function CreateInput(event) {
var key = event.keyCode;
var tbl=document.getElementById("tbl");
var str = "had a great time with @sarah333 and @kevin0955 at beach.";
replacedStr = str.replace(/\s\@(.*?)(\s|$)/g, ' <a href="http://example.com/$1">$1</a>$2');
if(key == 13)
{
tbl.innerHTML += replacedStr;
}
}
</script>
</head>
<body onKeypress="CreateInput(event)">
<table id="tbl">
</table>
</body>
</html>