Home > database >  Can't replace '\n' character in the end of string with regex and replace method
Can't replace '\n' character in the end of string with regex and replace method

Time:03-16

I used replace method of regex to replace the last character of a string. ex:

'hello'.replace(/o$/, '')
// result: hell

But when I try to replace '\n' at the end of the string

'sometext\nsometext\nsometext\n'.replace(/\\n$/, '')
// expects result: 'sometext\nsometext\nsometext'

It didn't work. i test this regex /\\n$/ with

https://regex101.com/r/jM4eNQ/1. Can anyone explain it to me

Thanks for your help.

CodePudding user response:

When you have \n inside a string, it is treated as a whitespace newline character.

So to match it you have to use the normal \n and you cant treat it as a string char and find it with escaping \\n.

let text = "something\nanotherline"
console.log(text)
//result: here \n is treated as a new line
//something
//anotherline

console.log(text.replace(/\n/, ""))
//result: somethinganotherline

text = "something\nsomething\nsomething\n"
console.log(text)
//something
//something
//something

//to remove newline from the end of a line use this:
console.log(text.replace(/\n$/, ""))
// the above but with newline removed from the end of text

CodePudding user response:

You can use the below regular expression with the 's' flag as a parameter. The 's' flag matches all characters including the newline.

'sometext\nsometext\nsometext\n'.replace(new RegExp(/.$/, 's'), '');

Documentation reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/dotAll

  • Related