Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?
-
Is it always the last character of the string? If not, have a look at string.lastIndexOf(searchstring, start)– skarmatsMar 31, 2011 at 8:56
-
1you don't need jQuery.– zzzzBovFeb 19, 2013 at 22:41
-
possible duplicate of How to replace last occurrence of characters in a string using javascript– Anderson GreenSep 4, 2014 at 5:41
11 Answers
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
-
2@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? Dec 18, 2012 at 10:07
-
1@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 thereplaceMe
variable so it doesn't contain special characters that will alter the regular expression Dec 18, 2012 at 18:38 -
@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+"]*)$");
Dec 19, 2012 at 8:33 -
1@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 Dec 19, 2012 at 22:57
-
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)
)
-
7+1 for "no need for jQuery". Its important to know that not JQuery isn't the answer to everything. Javascript is a perfectly capable programming language without having to push everything through jquery.– SpudleyMar 31, 2011 at 8:57
-
1@Spudley So true. However here at SO, no JS answer is complete without a jQuery version ;)) Mar 31, 2011 at 8:58
-
5
+1
for no regex &lastIndexOf(...)
does the search from the END (better performance) so the currently accepted regexp even can't be faster.– jave.webSep 23, 2016 at 13:22 -
"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.– tedebusJun 10, 2019 at 13:32
-
@tedebus please read the question. Also some of the examples can handle any last character Jun 10, 2019 at 13:34
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!
Another super clear way of doing this could be as follows:
let modifiedString = originalString .split('').reverse().join('') .replace('_', '') .split('').reverse().join('')
Keep it simple
var someString = "a_b_c";
var newCharacter = "+";
var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);
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() // "$$$"
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?
// 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 :)'
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
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);
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)
-
This was not what was asked. I answered what what asked and I guess I got a downvote from you. Also endsWith is not compatible with IE Jun 11, 2019 at 6:54