Remove Last Character From String If It's a "!" Using For-Loop - JavaScript

string remove last character python
remove last character from string javascript
remove last character from string in java
remove last character from string in excel
remove last character from string c++
string remove last character c#
remove last character from string sql
remove last character from string swift

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?

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;
}

How to remove the last character from a string?, Java's built-in method substring() of the class String is the most known way of how to remove the last character. This is done by getting from the existing String all� Method 1: Remove first or last x characters from text strings with formulas . Method 2: Remove first or last x characters from text strings with User Defined Function . Method 3: Remove first, last x characters or certain position characters without any formulas. Method 4: Remove both first x and last x characters from text strings with formula

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;
  }
}

Ways how to remove last character from String in Java, Please note that this method is not thread safe and it will fail with empty or null String. So here is java program to remove last character from� trim and rtrim do not remove the last character in a string. Although sometimes that is all they do, they will often remove many characters from the string. e.g. rtrim ('Assess','s') gives you 'Asse', not 'Asses'. That's why this answer is better than the accepted answer. – Buttle Butkus Mar 20 '15 at 4:52

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!!!!!"));

Java remove last character from string, Using String.substring(). The easiest and quickest way to remove the last character from a string is by using the String� run; I need the last character in the string to be removed only if it is a '+'. Some observations don't end in a '+' and those should be left as is. Also the '+' in other positions in the variable should be left as is, only if it is in the last position, it needs to be remove.

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;
}

Remove the last character of a string in Java, Question: How do I remove last character from a string in JavaScript or Node.js script? This tutorial When you can store in a variable. Syntax:. 'How to remove the last character in a string' is a general problem that we usually face while developing a dynamic SQL string or sometimes due to legacy data etc. Given below are multiple solutions to remove the last character from a string. SOLUTION 1 : Using LEFT string function. Given below is the script.…

@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;
}

2 Methods to Remove Last Character from String in JavaScript , You can use the substring() method of java.lang.String class to remove the first or last character of String in Java. The substring() method is� strgroupids = strgroupids.Remove(strgroupids.Length - 1); MSDN: String.Remove(Int32): Deletes all the characters from this string beginning at a specified position and continuing through the last position

How to Remove First and Last Character of String in , The StringBuffer class contains a method known as deleteCharAt(). This method deletes the character at a specified index/position. You can� Delete last/first character if it is a comma or certain character with formula You can apply the following formulas to delete the last or first character if it is a comma or certain character in Excel. Delete the last character if it is a comma 1.

How to remove the last character from a string in Java?, In this post, we will see how to remove last character from a string in JavaScript. It is not possible to in-place remove characters from a string since strings are� A simple regular expression of “.$”will match the last character in a string. The dollar sign means match from the end of the string, and a period (or dot) means any single character. Therefore, the following command will replace the last character with nothing, and effectively remove the last letter of the string:

Remove last character from a string in JavaScript, If my string is "abcdefghij" (I do not want to replace the 'j' character, since my string may contain multiple 'j' characters) I only want the last� The String.TrimEnd method removes characters from the end of a string, creating a new string object. An array of characters is passed to this method to specify the characters to be removed. The order of the elements in the character array does not affect the trim operation. The trim stops when a character not specified in the array is found.

Comments
  • Simplified using String.replace -- s = s.replace(/!+$/g, '')?
  • @31piy why does that work and s = s.replace("!", ""); does not?
  • Read about it here. It clearly says "If pattern is a string, only the first occurrence will be replaced".
  • 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.
  • 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).
  • Oh so I would have needed to decrease while looping i-- instead of increasing.
  • @HappyHands31 - Well, again, i isn't doing anything useful for you in the loop. If you have to use a for loop, I'd use for( ; s && s.slice(-1) === '!"; ) { s = s.substring(0, s.length - 1); } but really that's a while in disguise.
  • I don't understand - this returns isl!!!! - only removes one "!" when there isn't a for-loop?
  • This works: function remove(s) { return s.replace(/!+$/, ''); } - but I don't understand how that's only removing the instances of "!" that are at the end of the string.
  • my bad i thought you want to last character to be removed only once.
  • last character must always be removed if it's a "!"
  • stackoverflow.com/questions/55595859/…