Use global regex, instead of strings :
input = input.replace(/<div>/g, '');
input = input.replace(/<\/div>/g, '<br>');
console.log(input); // Many<br>Lines<br>Goes<br>Here<br>
More details :
replace() function can take, as first parameter :
- a String, like
'</div>'
- a RegExp, like
/<\/div>/
Whatever you're using a String or a RegExp, replace()
will find the first match, and replace it. The first match only.
You need to specify that the replace is global (ie. every match should be replaced).
You've got two options to make a global replace :
- Use regex flags :
input.replace(/<\/div>/g, '<br>');
- Use the third parameter, which is a comination of flags :
input.replace('</div>', '<br>', 'g');
Warning :
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.
As the third parameter way is not a standart, you're encouraged to use RegExp way.
Just for fun :
You also can do it in a single line :
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 ''
}
);
*/
would be. – Rob Dec 10 '13 at 11:04
` unless you're using XHTML. The solidus at the end is *tolerated* in HTML on void elements; that's all. It has exactly zero effect. – T.J. Crowder Dec 10 '13 at 11:05