0

I have string 101000 or 1010100 in which I am trying to replace 100 recursively using function remove data. The function removedata should return "yes" when string is empty and "no" when string is not empty while replacing it with value 100.

It works fine for string 1010100. It returns "no" but not for string 101000 where it becomes empty.

console.log(removedata("1010100"));
console.log(removedata("101000"));

function removedata(data) {
  data = data.replace("100", "");
  if (data.length == 0) {
    return "yes";
  } else {
    if (data.indexOf("100") > -1 && data.length > 0) {
      removedata(data);
    } else {
      return "no";
    }
  }
}

when 1010100 it returns no but when 101000 it returns undefined

4
  • so you want to remove all occurrences of '100' like: 100a100b1001c should become ab1c ? Commented Apr 21, 2019 at 20:49
  • 4
    removedata(data) should be return removedata(data) Commented Apr 21, 2019 at 20:50
  • wouldn't regex greatly simplify this? data = data.replace(/100/g, ""); Commented Apr 21, 2019 at 20:55
  • @AnduAndrici "101000".replace(/100/g, "") == "100". Commented Apr 21, 2019 at 20:57

2 Answers 2

3

You need to return the recursive call:

console.log(removedata("1010100"));
console.log(removedata("101000"));

function removedata(data) {
  data = data.replace("100", "");
  if (data.length == 0) {
    return "yes";
  } else {
    if (data.indexOf("100") > -1 && data.length > 0) {
      return removedata(data);
    } else {
      return "no";
    }
  }
}

Now it returns yes for the second one because all of the 100s have been removed and the string is empty.

Sign up to request clarification or add additional context in comments.

Comments

0
function removedata(data) {
  data = data.replace("100", "");
  if (data.length == 0) {
    return "yes";
  } else {
    if (data.indexOf("100") > -1 && data.length > 0) {
      removedata(data);                                     // This branch does not return anything
    } else {
      return "no";
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.