3

How do we replace last character of a string?

SetCookie('pre_checkbox', "111111111111 11   ")
    checkbox_data1 = GetCookie('pre_checkbox');

    if(checkbox_data1[checkbox_data1.length-1]==" "){
         checkbox_data1[checkbox_data1.length-1]= '1';
         console.log(checkbox_data1+"after");

    }

out put on console : 111111111111 11   after

Last character was not replaced by '1' dont know why

also tried : checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-1), "1");

could some one pls help me out

7
  • 5
    Strings are immutable. Commented Jul 31, 2013 at 14:43
  • immutable only means a new memory location is allocated for a changed string. Doesnt mean you cannot change a string. Commented Jul 31, 2013 at 14:44
  • 1
    @SujeshArukil: "Doesnt mean you cannot change a string"...? That is precisely what immutable means. You can assign a different string, but you can't change the original. And JS won't do the reassignment for you except in certain cases (like str += something), as pass-by-value languages like JS won't let the callee just up and change the caller's variables. Commented Jul 31, 2013 at 14:47
  • 1
    that is correct. All I meant was, the op wants to replace a character. What you get back would be a new string, not the modified original string. The original string cannot be updated, but a new string with the value replaced can be created. Commented Jul 31, 2013 at 14:54
  • 1
    @SujeshArukil: If you call a function that does the replacement and returns you a new string, or use + to create a string with additional chars, then yes. You can assign it to the variable/property that held the original, and it looks changed. But for example, str[0] = 'x' will not work; it just silently fails, as a string's indexes are not writable. It has to be done another way. Commented Jul 31, 2013 at 15:07

6 Answers 6

5

Simple regex replace should do what you want:

checkbox_data1 = checkbox_data1.replace(/.$/,1);

Generic version:

mystr = mystr.replace(/.$/,"replacement");

Remember that just calling str.replace() doesn't apply the change to str unless you do str = str.replace() - that is, apply the replace() function's return value back to the variable str

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

5 Comments

Just to be clear: It's not the regexp that solves the problem, but the assignment of the replace's return value to the original variable name.
@RobW Yes, I have clarified that fact with a final sentence
@SmokeyPHP ..just an extension to this question ..... say if i want to replace a space which is in the middle say at 3rd position for example : "ab c d" ...how do we do that ?
@user2569524 str = str.replace(/^(..)./,'$1'+'replacement') if the third is to be replaced -- ^ is the start of the string, . means any character, and the $1 is putting back into the string the 2 characters matched in (..)
@user2569524 Sorry just noticed you specified a space, previous code should be str = str.replace(/^(..) /,'$1'+'replacement')
1

use regex...

var checkbox_data1 = '111111111111 11   ';
checkbox_data1.replace(/ $/,'$1');
console.log(checkbox_data1);

This will replace the last space in the string.

Comments

0

You have some space in our string please try it

checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-4), "1   ");

then add the space in

console.log(checkbox_data1+"   after");

Comments

0

This is also a way, without regexp :)

var string = '111111111111 11   ';
var tempstr = '';
if (string[string.length - 1] === ' ') {
    for (i = 0; i < string.length - 1; i += 1) {
        tempstr += string[i];
    }
    tempstr += '1';
}

4 Comments

What is your intention? abcdefghdesiredValues is not the desired result.
I guess he can get the desired result out from the current code.
On console.log it appears (string - 1) + '1'. I don't know what you mean by string+'1'. You can log this code and see the result.
Why would you bother tacking on each character like this, when you could just say str = str.substring(0, str.length - 1) + '1'? Read about Schlemiel the Painter's Algorithm.
0

You can try this,

var checkbox_data1=checkbox_data1.replace(checkbox_data1.slice(-1),"+");

This will replace the last character of Your string with "+".

1 Comment

Not quite. It'll replace the first instance of the string's last character. If the string is '11111111 111 ', the first space (that is, the 9th character in the string) is what will get replaced.
0

As Rob said, strings are immutable. Ex:

var str = "abc";
str[0] = "d";
console.log(str); // "abc" not "dbc"

You could do:

var str = "111 ";
str = str.substr(0, str.length-1) + "1"; // this makes a _new_ string

1 Comment

Note, IE doesn't support negative numbers with substr. str.substr(0, -1) gives me "". (Plus, substr isn't defined by ECMAScript anyway; it's just a common addition. If you're going to start at 0, then substring does the same thing and is standardized.)

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.