输入:
<div>Many</div><div>Lines</div><div>Goes</div><div>Here</div>
预期输出:
Many<br>Lines<br>Goes<br>Here
我试过这样的方法:
input = input.replace("<div>", ""),
input = input.replace("</div>", "<br>")
虽然这可行,但解决方案并不是最优的。
干杯
最佳答案
使用全局正则表达式,而不是字符串:
input = input.replace(/<div>/g, '');
input = input.replace(/<\/div>/g, '<br>');
console.log(input); // Many<br>Lines<br>Goes<br>Here<br>
更多详情:
replace()函数可以作为第一个参数:
- 一个字符串,例如
'</div>'
- 正则表达式,例如
/<\/div>/
无论您使用的是字符串还是正则表达式,replace()
将找到第一个匹配项,并替换它。 仅限第一场比赛。
您需要指定替换是全局的(即应替换每个匹配项)。
您有两种选择来进行全局替换:
- 使用正则表达式标志:
input.replace(/<\/div>/g, '<br>');
- 使用第三个参数,它是标志的组合:
input.replace('</div>', '<br>', 'g');
警告:
The use of the flags parameter in the String.replace method is non-standard. Instead of using this parameter, use a RegExp object with the corresponding flags.
由于第三个参数方式不是标准,建议您使用RegExp方式。
纯属娱乐:
你也可以在一行中完成:
input = input.replace(/<(\/)?div>/g, function(m, p) { return p ? '<br>' : ''; });
/*
input.replace(
/<(\/)?div>/g, -> regex to match '<div>' and '</div>'
function(m, p) { -> m = whole match, p = first capturing group
return p -> if p is defined, ie. if we've got a slash
? '<br>' -> we matched '</div>', return '<br>'
: ''; -> we matched '<div>', return ''
}
);
*/
关于javascript - 正则表达式将 <div> 转换为 <br>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20492650/