Home > Back-end >  Replacing linefeeds but not \n in a variable (JavaScript)
Replacing linefeeds but not \n in a variable (JavaScript)

Time:09-10

In this case, I want to replace linefeeds(\n) to @ but not \n used inside the variable. Are there any ways to distinguish linefeeds from \n inside the code?

For example, I don't want to replace \n inside this: alert("abc \n cde")

let my_code = `
    alert("abc \n cde");
    alert("efd \n hij");
    alert("klm \n opq");
    alert("stu \n vwx");
`;
console.log( my_code )
my_code = my_code.replace(/\n/g, '@');
console.log( my_code )

online code editor: https://jsfiddle.net/r6La9mz2/

CodePudding user response:

"\n" is a line-feed. If you want to write \n (a backslash and an 'n') in a string, you have to write "\\n", and thus

console.log("abc \\n cde".replace(/\n/g, '@'));

will output

abc \n cde

CodePudding user response:

It is not possible. Once you use \n in string literal or string template it is parsed the same way you'd "pressed enter" there:

`#
#` === `#\n#` // true

In your particular use-case/example it may help to replace only all newlines not preceded by a space (/(?<! )\n/g) sequences, provided the "real" newlines are not also preceded by spaces.

`a \n b
c \n d`.replace(/(?<! )\n/g,'@') 
===
`a 
 b@c 
 d` // true
  • Related