简体   繁体   中英

Replace A word In A String

I need to replace the word _New+Delivery; in a string with comma ( ',')

sample input string: XP_New+Delivery;HP_New+Delivery;LA_New;

expected output: XP,HP,LA_New;

But it is returning the same input as output, not replacing anything any idea?

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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