Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last character of string using JavaScript

I have a very small query. I tried using concat, charAt, slice and whatnot but I didn't get how to do it.

Here is my string:

var str1 = "Notion,Data,Identity," 

I want to replace the last , with a . it should look like this.

var str1 = "Notion,Data,Identity." 

Can someone let me know how to achieve this?

like image 475
Patrick Avatar asked Apr 14 '16 17:04

Patrick


People also ask

How do I cut the last character of a string in JavaScript?

To remove the last character from a string in JavaScript, you should use the slice() method. It takes two arguments: the start index and the end index. slice() supports negative indexing, which means that slice(0, -1) is equivalent to slice(0, str. length - 1) .

How do you find and replace a character in a string in JavaScript?

Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.

How do I change the last occurrence of a string in Java?

Find the index of the last occurrence of the substring. String myWord = "AAAAAasdas"; String toReplace = "AA"; String replacement = "BBB"; int start = myWord. lastIndexOf(toReplace);

How do I get the last 5 characters of a string?

To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.


1 Answers

You can do it with regex easily,

var str1 = "Notion,Data,Identity,".replace(/.$/,".") 

.$ will match any character at the end of a string.

like image 150
Rajaprabhu Aravindasamy Avatar answered Oct 04 '22 07:10

Rajaprabhu Aravindasamy