Replace last occurrence of character in string

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

What about this?

function replaceLast(x, y, z){
  var a = x.split("");
  a[x.lastIndexOf(y)] = z;
  return a.join("");
}

replaceLast("Hello world!", "l", "x"); // Hello worxd!

Solution 4 - Javascript

Another super clear way of doing this could be as follows:

> let modifiedString = originalString > .split('').reverse().join('') > .replace('_', '') > .split('').reverse().join('')

Solution 5 - Javascript

Keep it simple

var someString = "a_b_c";
var newCharacter = "+";

var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);

Solution 6 - Javascript

var someString = "(/n{})+++(/n{})---(/n{})$$$";
var toRemove = "(/n{})"; // should find & remove last occurrence 

function removeLast(s, r){
  s = s.split(r)
  return s.slice(0,-1).join(r) + s.pop()
}

console.log(
  removeLast(someString, toRemove)
)

Breakdown:

s = s.split(toRemove)         // ["", "+++", "---", "$$$"]
s.slice(0,-1)                 //  ["", "+++", "---"]   
s.slice(0,-1).join(toRemove)  // "})()+++})()---"
s.pop()                       //  "$$$"   

Solution 7 - Javascript

Reverse the string, replace the char, reverse the string.

Here is a post for reversing a string in javascript: https://stackoverflow.com/questions/958908/how-do-you-reverse-a-string-in-place-in-javascript

Solution 8 - Javascript

    // Define variables
    let haystack = 'I do not want to replace this, but this'
    let needle = 'this'
    let replacement = 'hey it works :)'
    
    // Reverse it
    haystack = Array.from(haystack).reverse().join('')
    needle = Array.from(needle).reverse().join('')
    replacement = Array.from(replacement).reverse().join('')
    
    // Make the replacement
    haystack = haystack.replace(needle, replacement)
    
    // Reverse it back
    let results = Array.from(haystack).reverse().join('')
    console.log(results)
    // 'I do not want to replace this, but hey it works :)'

Solution 9 - Javascript

This is very similar to mplungjan's answer, but can be a bit easier (especially if you need to do other string manipulation right after and want to keep it as an array) Anyway, I just thought I'd put it out there in case someone prefers it.

var str = 'a_b_c';
str = str.split(''); //['a','_','b','_','c']
str.splice(str.lastIndexOf('_'),1,'-'); //['a','_','b','-','c']
str = str.join(''); //'a_b-c'

The '_' can be swapped out with the char you want to replace

And the '-' can be replaced with the char or string you want to replace it with

Solution 10 - Javascript

You can use this code

var str="test_String_ABC";
var strReplacedWith=" and ";
var currentIndex = str.lastIndexOf("_");
str = str.substring(0, currentIndex) + strReplacedWith + str.substring(currentIndex + 1, str.length);

alert(str);

Solution 11 - Javascript

This is a recursive way that removes multiple occurrences of "endchar":

function TrimEnd(str, endchar) {
  while (str.endsWith(endchar) && str !== "" && endchar !== "") {
    str = str.slice(0, -1);
  }
  return str;
}

var res = TrimEnd("Look at me. I'm a string without dots at the end...", ".");
console.log(res)

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
QuestionCLiownView Question on Stackoverflow
Solution 1 - JavascriptMartin JespersenView Answer on Stackoverflow
Solution 2 - JavascriptmplungjanView Answer on Stackoverflow
Solution 3 - JavascriptHarry StevensView Answer on Stackoverflow
Solution 4 - JavascripttensaiView Answer on Stackoverflow
Solution 5 - JavascriptDinesh VermaView Answer on Stackoverflow
Solution 6 - JavascriptvsyncView Answer on Stackoverflow
Solution 7 - JavascriptsanonView Answer on Stackoverflow
Solution 8 - JavascriptSteffanView Answer on Stackoverflow
Solution 9 - JavascriptPartial ScienceView Answer on Stackoverflow
Solution 10 - JavascriptTabish UsmanView Answer on Stackoverflow
Solution 11 - JavascripttedebusView Answer on Stackoverflow