Javascript 替换字符串中最后一次出现的字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5497318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace last occurrence of character in string
提问by CLiown
Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?
javascript 中是否有一种简单的方法来替换给定字符串中最后一次出现的“_”(下划线)?
回答by Martin Jespersen
You don't need jQuery, just a regular expression.
你不需要 jQuery,只需要一个正则表达式。
This will remove the last underscore:
这将删除最后一个下划线:
var str = 'a_b_c';
console.log( str.replace(/_([^_]*)$/, '') ) //a_bc
This will replace it with the contents of the variable replacement
:
这将用变量的内容替换它replacement
:
var str = 'a_b_c',
replacement = '!';
console.log( str.replace(/_([^_]*)$/, replacement + '') ) //a_b!c
回答by mplungjan
No need for jQuery nor regex assuming the character you want to replace exists in the string
假设字符串中存在要替换的字符,则不需要 jQuery 或正则表达式
Replace last char in a string
替换字符串中的最后一个字符
str = str.substring(0,str.length-2)+otherchar
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)
)
回答by Harry Stevens
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!
回答by tensai
Another super clear way of doing this could be as follows:
这样做的另一种超级清晰的方法如下:
let modifiedString = originalString .split('').reverse().join('') .replace('_', '') .split('').reverse().join('')
let modifiedString = originalString .split('').reverse().join('') .replace('_', '') .split('').reverse().join('')
回答by sanon
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?
这是在 javascript 中反转字符串的帖子: How do you reverse a string in place in JavaScript?
回答by Dinesh Verma
Keep it simple
把事情简单化
var someString = "a_b_c";
var newCharacter = "+";
var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);
回答by Partial Science
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.
这与 mplungjan 的答案非常相似,但可能会更容易一些(特别是如果您之后需要进行其他字符串操作并希望将其保留为数组)无论如何,我只是想我会把它放在那里以防万一更喜欢它。
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
并且“-”可以替换为您想要替换的字符或字符串
回答by vsync
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() // "$$$"
回答by tedebus
This is a recursive way that removes multiple occurrences of "endchar":
这是一种删除多次出现的“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)
回答by Steffan
// 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 :)'