1

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

2
  • I think it is replacing only the first occurrence in let t = stringHTML.replace('</div><div>', '<br/>'); Commented Sep 6, 2018 at 4:40
  • 1
    @NambiMurugan Yeah, you need regexp with g flag to force .replace to do it multiple times. Commented Sep 6, 2018 at 4:41

3 Answers 3

1

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>'));

Sign up to request clarification or add additional context in comments.

1 Comment

Welcome @feedGit
1

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>"))

1 Comment

Anyway to remove <br/> at the end?
1

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));

1 Comment

Anyway to remove <br/> at the end?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.