简体   繁体   English

替换字符串中的单词

[英]Replace A word In A String

I need to replace the word _New+Delivery;我需要替换 _New+Delivery 这个词; in a string with comma ( ',')在带逗号 (',') 的字符串中

sample input string: XP_New+Delivery;HP_New+Delivery;LA_New;示例输入字符串: XP_New+Delivery;HP_New+Delivery;LA_New;

expected output: XP,HP,LA_New;预计 output: XP,HP,LA_New;

But it is returning the same input as output, not replacing anything any idea?但它返回与 output 相同的输入,没有替换任何想法?

 function myFunction() { var str = document.getElementById("demo").innerHTML; var res = str.replace(new RegExp('_New+Delivery;', 'gi'), ','); document.getElementById("demo").innerHTML = res; }
 <p id="demo">XP_New+Delivery;HP_New+Delivery;LA_New;</p> <button onclick="myFunction()">Try it</button>

May be not perfect way but it will work.可能不是完美的方法,但它会起作用。

 const sampleInput = "XP_New+Delivery;HP_New+Delivery;LA_New;"; const result = sampleInput.split('_New+Delivery;').join(','); console.log(result)
For your problem use following code 对于您的问题,请使用以下代码

 function myFunction() { var str = document.getElementById("demo").innerHTML; var res = str.split('_New+Delivery;').join(','); document.getElementById("demo").innerHTML = res; }
 <p id="demo">XP_New+Delivery;HP_New+Delivery;LA_New;</p> <button onclick="myFunction()">Try it</button>

The plus sign in regex means "Matches between one and unlimited times, as many times as possible, giving back as needed".正则表达式中的加号表示“匹配一次到无限次,尽可能多次,根据需要回馈”。 To use plus sign as is you need to escape it with special \ .要按原样使用加号,您需要使用特殊的\对其进行转义。

new RegExp('_New\+Delivery;', 'gi')

But in your example The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser.但在您的示例中,反斜杠由读取字符串的代码解释,而不是传递给正则表达式解析器。 You need to double escape the plus sign:您需要双重转义加号:

new RegExp('_New\\+Delivery;', 'gi')

Try this:试试这个:

 var str = "XP_New+Delivery;HP_New+Delivery;LA_New;"; var res = str.replace(/(_New\+Delivery;)/g, ","); console.log(res);

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

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