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)
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With