Issue
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/
Solution
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
Answered By - myf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.