替换并连接图像 HTML 字符串
Replace and Concat an image HTML String
我有一个名为 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
函数完成
相关文章:
- 将html元素插入到文本字符串中,以匹配另一个html字符串
- HTML字符串作为上下文
- 正在分析HTML字符串并从中进行选择
- 将GET请求(HTML字符串)转换为完整的DOM对象
- 在树枝模板上从数据库中解压缩HTML字符串
- 如何使用Razor显示模板将字符串转换为html字符串
- 如何在不打断标记的情况下突出显示html字符串中的文本
- 使用val()在jquery循环中设置html字符串的val
- 搜索并用jQuery替换整个HTML字符串
- 替换 html 字符串中的某些“<”和“>”
- Javascript-将包含变量的html字符串作为参数传递
- 如何用JavaScript替换HTML字符串
- 如何在我的模板(Angular2/TypeScript)中将HTML字符串转换为HTML
- 在HTML字符串的某个段落后插入HTML
- 使用 javascript 压缩包含嵌入图像的 HTML 字符串
- 需要使用Java编码/转义HTML字符串,并在JavaScript中解码HTML字符串
- 在不更改 HTML 的情况下操作 HTML 字符串的内容
- 使用JavaScript从HTML字符串中提取文本
- regex在JavaScript中拆分一个html字符串
- 创建HTML对象的Javascript与创建HTML字符串的比较