简体   繁体   中英

Separate string with HTML tag with Javascript

var str = '<h1>Header</h1><p>Paragraph</p>

I have a string str I want to separate h1 and p text.

Result:

var h = 'Header'
var p = 'Paragraph'

Is there any shortcut way? I tried it with for loop.

Here you go, without String manipulation:

 const str = '<h1>Header</h1><p>Paragraph</p>' const div = document.createElement('div'); div.innerHTML = str; const [h, p] = [...div.children].map(el=>el.textContent); console.log(h, p);

Or even cleaner, using the experimental DOMParser API:

 const doc = new DOMParser().parseFromString('<h1>Header</h1><p>Paragraph</p>', 'text/html'); const [h, p] = [...doc.body.children].map(el=>el.textContent); console.log(h, p);

Using jQuery:

var str = '<h1>Header</h1><p>Paragraph</p>'
var h = $.parseHTML( str )[0].innerText
var p = $.parseHTML( str )[1].innerText

Try regex:

 var str = '<h1>Header</h1><p>Paragraph</p>'; var result = str.match(/<([\\w]+)[^>]*>(.*?)<\\/([\\w]+)[^>]*>/g).map(function(val){ var pre = val.split('>')[1]; return pre.substr(0, pre.lastIndexOf('<')); }); console.log(JSON.stringify(result));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM