我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
我有一个字符串,比如Hello world我需要替换索引3处的char。如何通过指定索引替换字符?
var str = "hello world";
我需要这样的东西
str.replaceAt(0,"h");
当前回答
你不能。取位置前后的字符并连接成一个新字符串:
var s = "Hello world";
var index = 3;
s = s.substring(0, index) + 'x' + s.substring(index + 1);
其他回答
使用扩展语法,你可以将字符串转换为数组,在给定位置分配字符,然后转换回字符串:
Const STR = "hello world"; 函数replace (s, i, c) { Const arr =[…s];//将字符串转换为数组 Arr [i] = c;//在pos i处设置字符c 返回arr.join(”);//返回字符串 } //打印"hallo world" console.log(replace (str, 1, 'a'));
这类似于Array.splice:
String.prototype.splice = function (i, j, str) {
return this.substr(0, i) + str + this.substr(j, this.length);
};
我用负下标的安全方法
/**
* @param {string} str
* @param {number} index
* @param {string} replacement
* @returns {string}
*/
static replaceAt (str, index, replacement)
{
if (index < 0) index = str.length + index
if (index < 0 || index >= str.length) throw new Error(`Index (${index}) out of bounds "${str}"`)
return str.substring(0, index) + replacement + str.substring(index + 1)
}
像这样使用它:
replaceAt('my string', -1, 'G') // 'my strinG'
replaceAt('my string', 2, 'yy') // 'myyystring'
replaceAt('my string', 22, 'yy') // Uncaught Error: Index (22) out of bounds "my string"
概括Afanasii Kurakin的回答,我们有:
函数替换(str, index, ch) { 返回str.replace(/。/g, (c, i) => i == index ?Ch: c); } let str = 'Hello World'; str = replacat (str, 1, 'u'); console.log (str);// hello World
让我们展开并解释正则表达式和replace函数:
函数replace (str, index, newChar) { 函数替换符(origChar, strIndex) { if (strIndex === index) 返回newChar; 其他的 返回origChar; } 返回str.replace(/。/ g,替代者); } let str = 'Hello World'; str = replacat (str, 1, 'u'); console.log (str);// hello World
正则表达式。恰好匹配一个字符。g使它匹配for循环中的每个字符。给定原始字符和该字符在字符串中位置的下标,将调用replacement函数。我们用一个简单的if语句来决定返回的是origChar还是newChar。
谢谢你的回答!
我还稍微调整了它,使它更像数组。拼接方法(并考虑了@Ates的笔记):
spliceString=function(string, index, numToDelete, char) {
return string.substr(0, index) + char + string.substr(index+numToDelete);
}
var myString="hello world!";
spliceString(myString,myString.lastIndexOf('l'),2,'mhole'); // "hello wormhole!"