Home > Enterprise >  Why this regex returns character instead of newline
Why this regex returns character instead of newline

Time:10-31

I want to insert something just before "test", I use this regex and expected that it would return newline but it returns "h" so if I insert with replace method I would not actually insert before "test" as I want : where's the mistake ?

https://jsfiddle.net/y4qh629a/

  const test = `
  blah blah
  test blah blah`;

  const regex = /[^"]\s*(?=test)/;
  const match = test.match(regex);
  alert(match)

CodePudding user response:

Use a negative lookbehind instead:

(?!<=")\s*(?=test)

const test = `
      blah blah
      test blah blah`;

const regex = /(?!<=")\s*(?=test)/;
const match = test.match(regex);
console.log(match)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The negated character class [^"] consumes a single character other than an " char, in this example that is the h char.

If you want to add something before the match, you can use replace instead or concat the value returned by match (note that match returns an array, and that const test can not be overwritten)

In this case, you can capture the full match using. In the replacement use the full match using $&.

Note that there should be at least a single character other than " present, which can also be a whitspace char.

const test = `
  blah blah
  test blah blah`;


console.log(test.replace(/[^"]\s*(?=test)/, "$&[replacement]"));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If you also want to match test at the start of the string:

const test = `test here
  blah blah
  test blah blah`;

console.log(test.replace(/(?:^|[^"])\s*(?=test)/g, "$&[replacement]"));
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

[^"] matches a single character.

Maybe you want to match unlimited times? Just add a.e. [^"]

const regex = /[^"] \s*(?=test)/;

Fiddle

  • Related