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

241
Visualizações
How to match a regex pattern from a certain position in javascript?

I'm trying to match the markdown header using regex in javascript. A markdown header is a string starting from one or more # followed by one or more spaces and some more texts, like this:

## This is the title

The tricky thing is, I'm given a multi-line string and a 0-indexed start position, I need to check if the string starting from the given position starts with a markdown header. In other words, I need to write the following function:

/**
 * The function should return true in the following situations:
 * - text: "abc\n# My Title", startPos = 4
 * - text: "abc\n# My Title\nxyz", startPos = 4
 * 
 * The function should return false in the following situation:
 * - text "abc\n#My Title", startPos = 0
 */
function isMarkdownHeader(text, startPos) {
    ...
}

Here is what I've tried:

function isMarkdownHeader(text, startPos) {
    const pattern = new RegExp(`^[^]{${startPos}}(^#+)(\\s+)(.*$)`, 'm');
    return pattern.exec(text) != null;
}

console.log(isMarkdownHeader("abc\n## My Title\nxyz", 4)); // true
console.log(isMarkdownHeader("abc\n## My Title\nxyz", 0)); // true, which is incorrect.

The function should return false in the second invocation. But it didn't. Why? How can I make it work?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Solution using Regex

You can use

^.{4}(#+\s+.*)

And the function will look

function isMarkdownHeader(text, startPos) {
    const pattern = new RegExp(`^.{${startPos}}#+\\s+.*`, "s");
    return pattern.exec(text) != null;
}

isMarkdownHeader("abc\n## My Title\nxyz", 4)  // true
isMarkdownHeader("abc\n## My Title\nxyz", 0)  // false

NOTE: Here I have used s flag. Also, see the demo.

Solution using Slice

You can slice the input string before checking the validity.

function isMarkdownHeader(text, startPos) {
    const pattern = /^#+\s+.*/;
    return !!pattern.exec(text.slice(startPos));
}

isMarkdownHeader("abc\n## My Title\nxyz", 4)  // true
isMarkdownHeader("abc\n## My Title\nxyz", 0)  // false

Edit

isMarkdownHeader("abcd## My Title\nxyz", 4) should return false. With your code, the return value is true

That occurs because the stuff called newline and the \n character is not the same thing. \n in a string is a regular character of the newline and it becomes a newline after we print the string. So if if you want to match both of them then use

^.{4}(?:^|\n|\\n)(#+\s+.*)

Here I added (?:^|\n|\\n) pattern to the old one

  • (?: Non-capturing group
    • ^|\n|\\n Match start of a string or newline or \n character
  • ) Close non-capturing group

It matches for

  • abcd\n## My Title\nxyz
  • abcd⏎## My Title\nxyz where ⏎ is a newline

And it does not match for

  • abcd## My Title\nxyz

P.S. For matching abc\n## My Title\nxyz you have to use 3 as a startPos, not including the \n character.

function isMarkdownHeader(text, startPos) {
    const pattern = new RegExp(`^.{${startPos}}(?:^|\\n|\\\\n)(#+\\s+.*)`, "s");
    return pattern.exec(text) != null;
}

console.log(isMarkdownHeader("abc\n## My Title\nxyz", 3))  // true
console.log(isMarkdownHeader("abc\n## My Title\nxyz", 0))  // false
console.log(isMarkdownHeader("abcd## My Title\nxyz", 4))  // false
about 4 years ago · Juan Pablo Isaza Relatório

0

According to Regex101, the {0} quantifier causes the previous token to be ignored. There's no citation to back that, but I'll take them at their word.

That being so, you can check that your match starts at index 0 (which indicates that the string started with the correct number of ignored characters).

function isMarkdownHeader(text, startPos) {
    const pattern = new RegExp(`^[^]{${startPos}}(^#+)(\\s+)(.*$)`, 'm');
    const match = pattern.exec(text);
    return match?.index === 0;
}

console.log(isMarkdownHeader("abc\n## My Title\nxyz", 4)); // true
console.log(isMarkdownHeader("abc\n## My Title\nxyz", 0)); // now false
about 4 years ago · Juan Pablo Isaza Relatório

0

You don't need the regex to start at a certain position. You can just pass the substring starting at startPos:

return pattern.exec(text.substring(startPos)) != null;
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