Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

200
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda