替换并连接图像 HTML 字符串

Replace and Concat an image HTML String

本文关键字:HTML 字符串 图像 连接 替换      更新时间:2023-09-26

我有一个名为 Sport 的数组,其中包含近 20 个项目,我需要用全局替换替换 (/string/g) 替换图像 HTML 字符串,我的字符串包含 HTML 标记。这是一个示例:

//Sports array
var sport = ['soccer','tennis','pool','basketball'];
//Original string
var original = 'Hello, do you play <img width="20" src="img/soccer.png"/> ?';
//New string
var newstring;
//If original string contains an image html of some sports from array,replace with :sport[item]:
for (var i = 0; i < sport.Length; i++)
{
   newstring = original.replace('/<img width="20" src="img'/icons'/'+sport[i]+'.png"/>/g',':'+sport[i]+':');
}

所以,回顾一下...我需要替换这个

<img width="20" src="img/soccer.png"/>

对此

:soccer:

结果应该是:你好,你玩:足球:?

你必须替换这个:

newstring = original.replace('/<img width="20" src="img'/icons'/'+sport[i]+'.png"/>/g',':'+sport[i]+':');

对此:

newstring = original.replace(new RegExp('<img width="20" src="img'/icons'/'+sport[i]+'.png"'/>', 'g'),':'+sport[i]+':');

因为您无法在"内联"正则表达式中连接字符串(如果有人知道正确的名称,请发表评论):

// no quotes around pattern
newString = myString.replace(/pattern/g, "foo")

你应该看看这个答案:替换JavaScript中所有出现的字符串

<小时 />

编辑:

如果您在使用特殊字符时遇到问题(来自引用的答案):

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|'[']'/''])/g, "''$1");
}
function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

// Use :
var newString = replaceAll(myString,"pattern", "replace_with_this");

在您的示例中:

for (var i = 0; i < sport.length; i++)
{
    newstring = replaceAll(
                    // original String
                    original,
                    // pattern
                    '<img width="20" src="img/icons/'+sport[i]+'.png"/>',
                    // replace with :
                    ':'+sport[i]+':');
}

注意:replaceAll中,您不必转义模式,它由escapeRegExp函数完成