Replace last character of string using JavaScript

JavascriptString

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

You can do it with regex easily,

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

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

Solution 2 - Javascript

You can remove the last N characters of a string by using .slice(0, -N), and concatenate the new ending with +.

var str1 = "Notion,Data,Identity,";
var str2 = str1.slice(0, -1) + '.';
console.log(str2);

Notion,Data,Identity.

Negative arguments to slice represents offsets from the end of the string, instead of the beginning, so in this case we're asking for the slice of the string from the beginning to one-character-from-the-end.

Solution 3 - Javascript

This isn't elegant but it's reusable.

term(str, char)

str: string needing proper termination

char: character to terminate string with

var str1 = "Notion,Data,Identity,";

function term(str, char) {
  var xStr = str.substring(0, str.length - 1);
  return xStr + char;
}

console.log(term(str1,'.'))

Solution 4 - Javascript

You can use simple regular expression

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatrickView Question on Stackoverflow
Solution 1 - JavascriptRajaprabhu AravindasamyView Answer on Stackoverflow
Solution 2 - JavascriptJeremyView Answer on Stackoverflow
Solution 3 - Javascriptzer00neView Answer on Stackoverflow
Solution 4 - JavascriptMD SHAYONView Answer on Stackoverflow