I have a HTML string like this:
<div>My cat</div><div>My dog</div><div>12345</div>
I want to use Regex to replace globally string (change </div><div>
into <br/>
, then remove all HTML, just keep <br/>
only :
My cat<br/>My dog<br/>12345
I tried with this code:
var formatHTMLQuill = function (stringHTML) {
let t = stringHTML.replace('</div><div>', '<br/>');
let n = t.replace(/<(?!br\s*\/?)[^>]+>/g, '')
return n
}
But it's not work, result is My cat<br/>My dog</div><div>12345
You can remove <div>
first and replace </div>
with <br/>
var formatHTMLQuill = function (stringHTML) { let t = stringHTML.replace(/\\<div>/g, ''); let n = t.replace(/\\<\\/div>/g, '<br/>') return n } console.log(formatHTMLQuill("<div>test</div> <div>test1</div>"))
You can use RegEx with the global flag g
. The g
modifier is used to perform a global match (find all matches rather than stopping after the first match).
var html = `<div>My cat</div><div>My dog</div><div>12345</div>` var formatHTMLQuill = function (stringHTML) { let t = stringHTML.replace(/<div>/ig,'') //remove the start div .replace(/<\\/div>/ig, '<br/>') //replace the closing </div> .replace(/(<br\\/>\\s*)+$/,''); //remove the last <br/> return t; } console.log(formatHTMLQuill(html));
Please verify the below code:
var formatHTMLQuill = function (stringHTML) { let t = stringHTML.replace(/(<\\/div><div>)/g, '<br/>'); let n = t.replace(/(<\\/div>|<div>)/g, ''); return (n); } console.log(formatHTMLQuill('<div>My cat</div><div>My dog</div><div>12345</div>'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.