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?

>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 //

Leave a Reply