RegEx in JavaScript.split ()

I need to break a line like this

<p>foo</p><p>bar</p>

into an array with "foo" and "bar"

I thought RegEx might help me, but it seems I did not understand RegEx. This is my attempt.

var inputText = "<p>foo</p><p>bar</p>";
splittedSelection = inputText.split("/<p>|<\/p>/g");

But all I can achieve is a single record array, and this is the same as inputText.

I made a little violin for you.

Thanks for any help.

+4
source share
6 answers

Instead of internal quotes you should use /<p>|<\/p>/g. However, this will result in ["", "foo", "", "bar", ""], which is undesirable, so you can .filter()remove empty results, for example:

var inputText = "<p>foo</p><p>bar</p>";

splittedSelection = inputText.split(/<p>|<\/p>/g).filter(function(value) {
  // Filter out empty results
  return value !== "";
});

document.getElementById("bar").innerHTML += "0: " + splittedSelection[0] + "\n" + "1: " + splittedSelection[1] + "\n";
<div id="bar">
</div>
Run codeHide result
+1
source

you can start with something like this:

  • .+
  • .+? lazy quantifier

const text = "<p>foo</p><p>bar</p>";

const re = /<.+?>(.+?)<\/.+?>/g;

console.log(text.split(re).filter(t => t));
Hide result
+1

ES6:

const regex = /<[^>]*>/gi;
let string = '<p>foo</p><p>bar</p>';
let result = string.split(regex).filter(e => e);
0

, . .

textContent :

let res = Array.from(document.getElementsByTagName('p')).map(e => e.textContent);
console.log(res);
<p>foo</p><p>bar</p>
Hide result

, ( DOM):

let s = "<p>foo</p><p>bar</p>";
let el = document.createElement('div');
el.innerHTML = s;

let res = Array.from(el.getElementsByTagName('p')).map(e => e.textContent);
console.log(res);
Hide result

node, cheerio:

const cheerio = require('cheerio')
let html = "<p>foo</p><p>bar</p>";
const $ = cheerio.load(html);
let res = [];
$('p').each((i,e) => res.push($(e).text()));
console.log(res);

, , DOM/XML/HTML-.

0

, , jQuery regex.

var inputText = "<p>foo</p><p>bar</p>";
var splittedSelection = $('<div>'+inputText+'</div>').find("p").map(function() { 
  return $(this).text() 
});
$.each(splittedSelection, function(i,item) {
  $("#bar").append(i+": " +item + "<br/>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="bar"></div>
Hide result
0

:

let regex = /(?![<p>])(.*?)(?=[<\/p>])/g
  , inputText = "<p>foo</p><p>bar</p>";

let array = inputText.match(regex).filter(i => i);
  
console.log(array);
Hide result
0
source

Source: https://habr.com/ru/post/1682952/


All Articles