Replace last occurrence of character in string

Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?


You don't need jQuery, just a regular expression.

This will remove the last underscore:

var str = 'a_b_c';
console.log(  str.replace(/_([^_]*)$/, '$1')  ) //a_bc

This will replace it with the contents of the variable replacement:

var str = 'a_b_c',
    replacement = '!';

console.log(  str.replace(/_([^_]*)$/, replacement + '$1')  ) //a_b!c

No need for jQuery nor regex assuming the character you want to replace exists in the string

Replace last char in a string

str = str.substring(0,str.length-2)+otherchar

Replace last underscore in a string

var pos = str.lastIndexOf('_');
str = str.substring(0,pos) + otherchar + str.substring(pos+1)

or use one of the regular expressions from the other answers

var str1 = "Replace the full stop with a questionmark."
var str2 = "Replace last _ with another char other than the underscore _ near the end"

// Replace last char in a string

console.log(
  str1.substring(0,str1.length-2)+"?"
)  
// alternative syntax
console.log(
  str1.slice(0,-1)+"?"
)

// Replace last underscore in a string 

var pos = str2.lastIndexOf('_'), otherchar = "|";
console.log(
  str2.substring(0,pos) + otherchar + str2.substring(pos+1)
)
// alternative syntax

console.log(
  str2.slice(0,pos) + otherchar + str2.slice(pos+1)
)