skip to Main Content

Running into an issue doing a regex replacement…

the pattern [ ]+$ works fine in the VSCode editor but not when I put it in code:

data = `
Hello      
 World
test
.
`
console.log(data.replace(/[ ]+$/, ""))

If we run that snippet we can see that the regex did not do the replacements

Fresh out of ideas what could be the problem

2

Answers


  1. $ matches end of input string. You need to add m flag to RegEx for $ match end of line instead:

    data = `
    Hello      
     World
    test
    .
    `
    console.log(data.replace(/ +$/m, ""))
    Login or Signup to reply.
  2. ^ and $ anchor to the very start and end of the test string.

    You need to add the m flag, to make them work on a per line basis.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/multiline#description:

    The m flag indicates that a multiline input string should be treated as multiple lines. For example, if m is used, ^ and $ change from matching at only the start or end of the entire string to the start or end of any line within the string.

    data = `
    Hello      
     World
    test
    .
    `
    console.log(data.replace(/[ ]+$/m, ""))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search