Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda