Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?
This question is related to
javascript
// Define variables_x000D_
let haystack = 'I do not want to replace this, but this'_x000D_
let needle = 'this'_x000D_
let replacement = 'hey it works :)'_x000D_
_x000D_
// Reverse it_x000D_
haystack = Array.from(haystack).reverse().join('')_x000D_
needle = Array.from(needle).reverse().join('')_x000D_
replacement = Array.from(replacement).reverse().join('')_x000D_
_x000D_
// Make the replacement_x000D_
haystack = haystack.replace(needle, replacement)_x000D_
_x000D_
// Reverse it back_x000D_
let results = Array.from(haystack).reverse().join('')_x000D_
console.log(results)_x000D_
// 'I do not want to replace this, but hey it works :)'
_x000D_
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?
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{})$$$";_x000D_
var toRemove = "(/n{})"; // should find & remove last occurrence _x000D_
_x000D_
function removeLast(s, r){_x000D_
s = s.split(r)_x000D_
return s.slice(0,-1).join(r) + s.pop()_x000D_
}_x000D_
_x000D_
console.log(_x000D_
removeLast(someString, toRemove)_x000D_
)
_x000D_
s = s.split(toRemove) // ["", "+++", "---", "$$$"]
s.slice(0,-1) // ["", "+++", "---"]
s.slice(0,-1).join(toRemove) // "})()+++})()---"
s.pop() // "$$$"
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!
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';_x000D_
str = str.split(''); //['a','_','b','_','c']_x000D_
str.splice(str.lastIndexOf('_'),1,'-'); //['a','_','b','-','c']_x000D_
str = str.join(''); //'a_b-c'
_x000D_
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
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."_x000D_
var str2 = "Replace last _ with another char other than the underscore _ near the end"_x000D_
_x000D_
// Replace last char in a string_x000D_
_x000D_
console.log(_x000D_
str1.substring(0,str1.length-2)+"?"_x000D_
) _x000D_
// alternative syntax_x000D_
console.log(_x000D_
str1.slice(0,-1)+"?"_x000D_
)_x000D_
_x000D_
// Replace last underscore in a string _x000D_
_x000D_
var pos = str2.lastIndexOf('_'), otherchar = "|";_x000D_
console.log(_x000D_
str2.substring(0,pos) + otherchar + str2.substring(pos+1)_x000D_
)_x000D_
// alternative syntax_x000D_
_x000D_
console.log(_x000D_
str2.slice(0,pos) + otherchar + str2.slice(pos+1)_x000D_
)
_x000D_
Another super clear way of doing this could be as follows:
let modifiedString = originalString .split('').reverse().join('') .replace('_', '') .split('').reverse().join('')
This is a recursive way that removes multiple occurrences of "endchar":
function TrimEnd(str, endchar) {_x000D_
while (str.endsWith(endchar) && str !== "" && endchar !== "") {_x000D_
str = str.slice(0, -1);_x000D_
}_x000D_
return str;_x000D_
}_x000D_
_x000D_
var res = TrimEnd("Look at me. I'm a string without dots at the end...", ".");_x000D_
console.log(res)
_x000D_
You can use this code
var str="test_String_ABC";_x000D_
var strReplacedWith=" and ";_x000D_
var currentIndex = str.lastIndexOf("_");_x000D_
str = str.substring(0, currentIndex) + strReplacedWith + str.substring(currentIndex + 1, str.length);_x000D_
_x000D_
alert(str);
_x000D_
Source: Stackoverflow.com