103

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

2

9 Answers 9

169

You can use 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

Sign up to request clarification or add additional context in comments.

9 Comments

@Martin Jespersen: what if the text to be replaced is not the underscore but the content of a variable called replaceMe? How should the regex be modified?
@Pierpaolo: You'd have to create the regexp using a new RegExp, read all about it here: developer.mozilla.org/en-US/docs/JavaScript/Guide/… - Remember to escape the replaceMe variable so it doesn't contain special characters that will alter the regular expression
@Martin Jespersen: thanks for the link. I already knew about the new RegExp syntax. My question was more like "where should I put the variable replaceMe"? e.g.: var aRegExpr = new RegExp("_([^"+replaceMe+"]*)$");
@Pierpaolo: its not that simple tbh since you can have a word and not just a single char in a variable - you should start a new question about it :) It is too complicated for a comment here
Thanks. I understand, I will search whether there is already one.
|
79

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

5 Comments

+1 for no regex & lastIndexOf(...) does the search from the END (better performance) so the currently accepted regexp even can't be faster.
"nor regex".... this solution doesn't work if string doesn't contain the underscore. Regex version does. You can't add the substitution character if not needed.
@tedebus please read the question. Also some of the examples can handle any last character
@mplungjan I read the question. In fact, my objection is related to the term "occurrence": there may be the element to be eliminated, but also not. The solution I read here adds a character regardless of whether it is necessary or not. I was not referring to the fact that the character could be different.
Updated to include that the char needs to exist
14

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!

Comments

8

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

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

Comments

5

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()                       //  "$$$"   

Comments

2

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

Here is a post for reversing a string in javascript: How do you reverse a string in place in JavaScript?

Comments

2

    // 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 :)'

Comments

1

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

Comments

-2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.