Javascript替换字符串regex

Javascript replace string regex

本文关键字:regex 字符串 替换 Javascript      更新时间:2023-09-26

我有以下字符串

hello[code:1], world [code:2], hello world

我想将此字符串替换为

hello <a href="someurl/1">someothercode</a>, world <a href="someurl/2">someothercode</a>, hello world

我想要这个字符串转换使用javascript reg ex

我试过

/'[code:('d+)']/

reg ex,但不确定如何标记它们

这能满足您的需求吗?

mystring.replace(/'[code:([0-9]+)']/g, '<a href="someurl/$1">somelink</a>');

演示

var s = 'hello[code:1], world [code:2], hello world';
var codes = {
    1: '<a href="someurl/1">someothercode</a>',
    2: '<a href="someurl/2">someothercode</a>'
};
s = s.replace(/'[code:('d*)']/g, function(a, b) {
    return codes[b]
})
document.write(s)
​

您还不完全清楚自己想要什么,但这会输出您想要的结果:

"hello[code:1], world [code:2], hello world"
    .replace(/'[(.*?):(.*?)']/g, '<a href="someurl/$2">someother$1</a>')

输出:

'hello<a href="someurl/1">someothercode</a>, world <a href="someurl/2">someothercode</a>, hello world'