简体   繁体   English

将 \\n 或 \\r\\n 替换为<br />在 javascript 中使用变量

[英]Replacing \n or \r\n with <br /> in javascript by using variables

I am passing 2 variables to javascript function,我将 2 个变量传递给 javascript 函数,

  1. ReplaceTo = \\n/g替换为 = \\n/g

and

  1. ReplaceWith = <br />替换为 = <br />

Below is the sample input string, desired output and current code I am using, but it does not replace anything.下面是我正在使用的示例输入字符串、所需的输出和当前代码,但它不会替换任何内容。

Input String: Line 1\\nLine 2\\nLine 3\\n输入字符串: Line 1\\nLine 2\\nLine 3\\n

Desired Output String: Line 1<br/>Line 2<br/>Line 3<br/>所需的输出字符串: Line 1<br/>Line 2<br/>Line 3<br/>

var inputStr = "Line 1\nLine 2\nLine 3\n";
var ReplaceTo = "\n/g" ;
var ReplaceWith = "<br />";
inputStr = inputStr.replace(ReplaceTo, ReplaceWith);

I know that if I hard-code in the replace function like .replace(/\\\\n/g, <br />) it will work, but I need to use variables as I am passing values from config.我知道如果我在像.replace(/\\\\n/g, <br />)这样的替换函数中进行硬编码,它会起作用,但我需要使用变量,因为我从配置传递值。

Can some one please help how to replace using variables with these special characters.有人可以帮助如何用这些特殊字符替换 using 变量。

ReplaceTo must be a regex, not an string. ReplaceTo 必须是正则表达式,而不是字符串。 Here the working code这里的工作代码

 var inputStr = "Line 1\\nLine 2\\nLine 3\\n"; var inputReplace = new RegExp("\\\\n", 'g') var ReplaceWith = "<br />"; inputStr = inputStr.replace(inputReplace, ReplaceWith); console.log(inputStr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM