user2569524
user2569524

Reputation: 1751

Replacing the last character in a string javascript

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

Upvotes: 3

Views: 10212

Answers (6)

Halcyon
Halcyon

Reputation: 57709

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

Upvotes: 0

Hitesh
Hitesh

Reputation: 277

You can try this,

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

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

Upvotes: 0

sla55er
sla55er

Reputation: 811

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

Upvotes: 0

user1193035
user1193035

Reputation:

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

Upvotes: 0

Sujesh Arukil
Sujesh Arukil

Reputation: 2469

use regex...

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

This will replace the last space in the string.

Upvotes: 1

MDEV
MDEV

Reputation: 10838

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

Upvotes: 5

Related Questions