Regex Split Between Text and HTML Tags

/* This is the same as this PHP version: $test = 'foo <a b="c">bar</a> baz <b> qux yo"s <c><d> wut?'; $results = preg_split('#(<\/?[-:\w]+(?:>|\s[^<>]*?>))#', $test, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); */ var test = 'foo <a b="c">bar</a> baz <b> qux yo"s <c><d> wut?'; var results = []; test.replace(/([^<>]*?)(<\/?[-:\w]+(?:>|\s[^<>]*?>)|$)/g, function(a, b, c) { if (b) results.push(b); if (c) results.push(c); }); console.log(results); /* [ 'foo ', '<a b="c">', 'bar', '</a>', ' baz ', '<b>', ' qux yo"s ', '<c>', '<d>', ' wut?' ] */ // example usage: replace all `"` character(s) outside the HTML tag(s) with `♥` var output = ""; for (var i = 0, len = results.length; i < len; ++i) { var s = results[i]; // Is this a HTML tag or text? if (s && s[0] === '<' && s.slice(-1) === '>') { // this is a HTML tag … output += s; } else { // do something with text … output += s.replace(/"/g, '♥'); } } console.log(output); // READ MORE: <http://www.dte.web.id/2016/07/regex-extract-html-tag-from-string.html>
Safe string replace helper.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.