替换字符串中字符的最后一个匹配项

在 javascript 中有没有一种简单的方法来替换给定字符串中最后出现的’_’(下划线) ?

128549 次浏览

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

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

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

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

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';
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

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

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

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