Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 462
Vishnu Sajeevan Avatar asked Dec 10 '25 11:12

Vishnu Sajeevan


2 Answers

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>
like image 54
niksan karkee Avatar answered Dec 12 '25 00:12

niksan karkee


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')
like image 33
Urmat Zhenaliev Avatar answered Dec 12 '25 01:12

Urmat Zhenaliev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!