admin管理员组

文章数量:1388903

I have

function remove(s) {

    for (i = 0; i < s.length; i++) {

        let lastChar = s.slice(-1);

        if (lastChar === "!") {
            s = s.substring(0, s.length - 1);
        }
        else {
            return s;
        }
    }
  return s;
}

And this is passing 105 tests but failing 1 on codewars.

The test that it's failing is:

Expected: '\'isl\'', instead got: '\'isl!\'' for when (s) is "isl!!!!!"

I can't figure out why, in this case, it's not removing the last character in the string.

This should be removing the last character in the string whenever it's !:

if (lastChar === "!") {
            s = s.substring(0, s.length - 1);
        }

I've also tried:

s = s.replace("!", "");

But same result. Any ideas?

I have

function remove(s) {

    for (i = 0; i < s.length; i++) {

        let lastChar = s.slice(-1);

        if (lastChar === "!") {
            s = s.substring(0, s.length - 1);
        }
        else {
            return s;
        }
    }
  return s;
}

And this is passing 105 tests but failing 1 on codewars.

The test that it's failing is:

Expected: '\'isl\'', instead got: '\'isl!\'' for when (s) is "isl!!!!!"

I can't figure out why, in this case, it's not removing the last character in the string.

This should be removing the last character in the string whenever it's !:

if (lastChar === "!") {
            s = s.substring(0, s.length - 1);
        }

I've also tried:

s = s.replace("!", "");

But same result. Any ideas?

Share Improve this question asked Apr 9, 2019 at 15:03 HappyHands31HappyHands31 4,10119 gold badges65 silver badges117 bronze badges 5
  • 1 Simplified using String.replace -- s = s.replace(/!+$/g, '')? – 31piy Commented Apr 9, 2019 at 15:05
  • @31piy why does that work and s = s.replace("!", ""); does not? – HappyHands31 Commented Apr 9, 2019 at 15:06
  • 2 Read about it here. It clearly says "If pattern is a string, only the first occurrence will be replaced". – 31piy Commented Apr 9, 2019 at 15:08
  • Right so then s = s.replace(/!+$/g, '') works when i++ and s = s.replace("!", ""); works when i-- - this is really the answer to my question. If you want to post an answer I'll gladly accept it. – HappyHands31 Commented Apr 9, 2019 at 15:40
  • You don't really need any loop when using String.replace method. If the excercise needs that you do it with a loop, then you should follow the approach suggested by T.J. Crowder (or others, whatever you prefer). – 31piy Commented Apr 10, 2019 at 3:36
Add a ment  | 

5 Answers 5

Reset to default 3

Because you're increasing i and checking i < s.length on each loop. At one point, you remove a ! (thus shortening the string) and i is equal to s.length and you never check the last char.

There's no reason for i at all. (Or a for loop, but if that was the requirement in the challenge...)

If you step through it with your debugger, you'll see the problem. This version using console.log also shows the problem:

function remove(s) {

    for (i = 0; i < s.length; i++) {

        let lastChar = s.slice(-1);

        if (lastChar === "!") {
            s = s.substring(0, s.length - 1);
            console.log(`i = ${i}, s = '${s}', s.substring(i) = '${s.substring(i)}'`);
        }
        else {
            console.log(`returning '${s}'`);
            return s;
        }
    }
  console.log(`returning '${s}' at end, because ${i} >= ${s.length}`);
  return s;
}
remove("isl!!!!!");
.as-console-wrapper {
  max-height: 100% !important;
}

You can do this without using for loop.

const stringRemover (str) => {
  if (str[str.length-1] === "!") {
    return str.slice(0,str.length-1);
  } else {
    return str;
  }
}

You can create a recursive function and check if the last char using CharAt if it is !. If it is so then again call the same function but with new string which is created after removing the last !

Not sure why the for is needed if the last character is needed

function remove(str) {

  let getLastChar = str.charAt(str.length - 1);
  if (getLastChar === '!') {
    return remove(str.substring(0, str.length - 1))
  } else {
    return str;
  }

}

console.log(remove("isl!!!!!"));

Here is codewars result

Here is result

As answered in a previous reply, i < s.length is checked in every iteration in a for loop. Try this :

function remove(s) {

    let a = s.length;

    for (i = 0; i < a; i++) {

        let lastChar = s.slice(-1);

        if (lastChar === "!") {
            s = s.substring(0, s.length - 1);
        }
        else {
            return s;
        }
    }
  return s;
}

@T.J. Crowder pointed me in the right direction, but he didn't provide an answer that followed my original logic (in this case I wanted to use a for-loop).

The key takeaway is that s = s.replace("!", ""); will work when i-- and s = s.replace(/!+$/g, '') will work when i++. Because, as far as I understand, the replace() method only replaces the first occurrence of the string, which is why we need i-- to force the loop to iterate backwards through the string, making sure that every occurance of "!" gets replaced.

I.e. this will work:

function remove(s) {

    for (i = 0; i < s.length; i--) {

        let lastChar = s.slice(-1);

        if (lastChar === "!") {
            s = s.replace("!", '')
        }
        else {
            return s;
        }
    }
    return s;
}

And this will also work:

function remove(s) {

    for (i = 0; i < s.length; i++) {

        let lastChar = s.slice(-1);

        if (lastChar === "!") {
            s = s.replace(/!+$/g, '');
        }
        else {
            return s;
        }
    }
    return s;
}

本文标签: Remove Last Character From String If It39s a quotquot Using ForLoopJavaScriptStack Overflow