Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript regex replace trimming trailing white spaces

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Fresh out of ideas what could be the problem

>Solution :

^ 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, ""))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading