输入:
<div>Many</div><div>Lines</div><div>Goes</div><div>Here</div>
Run Code Online (Sandbox Code Playgroud)
预期输出:
Many<br>Lines<br>Goes<br>Here
Run Code Online (Sandbox Code Playgroud)
我尝试了这样的方法:
input = input.replace("<div>", ""),
input = input.replace("</div>", "<br>")
Run Code Online (Sandbox Code Playgroud)
虽然这有效,但解决方案并不是最佳的。
干杯
使用全局正则表达式,而不是字符串:
input = input.replace(/<div>/g, '');
input = input.replace(/<\/div>/g, '<br>');
console.log(input); // Many<br>Lines<br>Goes<br>Here<br>
Run Code Online (Sandbox Code Playgroud)
replace()函数可以作为第一个参数:
'</div>'/<\/div>/无论您使用 String 还是 RegExp,replace()都会找到第一个匹配项并替换它。只有第一场比赛。
您需要指定替换是全局的(即应该替换每个匹配项)。
您有两个选项可以进行全局替换:
input.replace(/<\/div>/g, '<br>');input.replace('</div>', '<br>', 'g');在 String.replace 方法中使用 flags 参数是非标准的。不要使用此参数,而是使用带有相应标志的 RegExp 对象。
由于第三个参数方式不是标准的,我们鼓励您使用 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 ''
}
);
*/
Run Code Online (Sandbox Code Playgroud)