Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing the last character in a string javascript

Tags:

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

like image 698
user2569524 Avatar asked Dec 10 '25 10:12

user2569524


2 Answers

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

like image 141
MDEV Avatar answered Dec 12 '25 09:12

MDEV


use regex...

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

This will replace the last space in the string.

like image 39
Sujesh Arukil Avatar answered Dec 12 '25 08:12

Sujesh Arukil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!