Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
Get a specific item from a string in JavaScript

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

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>'));
console.log(isWrapped('<p'));

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!