Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The replace method when the string is found

I’m trying to make a replace function with javascript, but it will give an error if the one to replace doesn’t exist, like below:

var string1 = "hello";
var string2 = "<b>Hello</b>";

alert(string1.replace(/<b>?|<\/b>?/g, "")); // this is work //
alert(string2.replace(/<b>?|<\/b>?/g, "")) // this is error //

So when the tag is not found it throws an error, how to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Based on the description of your post, you want there to be an error thrown when there are no replacements made, so your "this is work" and "this is error" comments are backwards. If that’s incorrect, just change === to !== and reword the "No replacements made" (but at that point, you probably want to use RegExp.prototype.test() instead of .replace)

var string1 = "hello";
var string2 = "<b>Hello</b>";

function customReplace(text, regex, replacement) {
  var replaced = text.replace(regex, replacement);
  if (text === replaced) {
    throw new Error("No replacements made");
  }
  return replaced;
}

// I changed the order here since string1 should throw an error
console.log(customReplace(string2, /<b>?|<\/b>?/g, "")) // this one does not throw an error //
console.log(customReplace(string1, /<b>?|<\/b>?/g, "")); // this one throws an error //
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading