Home > Software engineering >  Get a specific item from a string in JavaScript
Get a specific item from a string in JavaScript

Time:11-05

I want to check if the first item from the string is wrapped in HYML tags. I can have the next situations:

  1. "nothtml <p>" // expect false
  2. "<p> " //expect true
  3. " <p> " //expect true
  4. "<span>text " //expect true
    In all situations i need to get the expected value.

const s = '<p>test <p>';

console.log(s.split('<'))
console.log(/<\/?[a-z][\s\S]*>/i.test(s[0]));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

According to the above idea, i want to split() the string and to get the first element, but i can't manage all situations when the first item could be not only <p>, but also <span>, <div>, how you can notice the length of the html tag can be different. Basically i need to find a solution to split the elements that are wrapped in tags <element>. How to do that?

CodePudding user response:

You can use regular expressions to test your string.

See below regex, it checks if it's starting with HTML tag element with ignoring any space before the tag

/^\s*(\<\w \>[\s\S]*\<\/\w \>)/.test("nothtml <p>") // return false

and if you want to get the element

/^\s*(\<\w \>[\s\S]*\<\/\w \>)/.exec("      <element>dsa</element>")[1]

feel free to update the regular expression based on your needs, there are plenty of examples over the internet of how to validate HTML string using regular expressions.

CodePudding user response:

Here is the approach I suggested in the comments, namely to parse text as HTML and inspect the first node. This example assumes a browser environment but there are HTML parsers available for Node.js as well. It also assumes that the input can be parsed as HTML.

function isWrapped(text) {
  const container = document.createElement('div');
  container.innerHTML = text.trimStart();
  return container.childNodes[0].nodeType === Node.ELEMENT_NODE; 
}

console.log(isWrapped('foo <p>test</p>'));
console.log(isWrapped('<p>test</p>'));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related