为什么我在使用 str.replace() 时得到错误的输出?
Why am I getting the wrong output while using str.replace()?
我的代码有一个指向字符串中字符的索引值,我必须用前一个值和下一个值交替替换该字符的所有实例,给定索引字符的值除外。下面是我实现这个的代码:
function replaceChar(string,idx){
a = string[idx]
b= []
pre_val = string[idx - 1]
post_val = string[idx + 1]
for(let i=0; i< string.length ; i++){
if(i==idx){
continue
}
if (string[i]===a){
b.push(i)
}
}
for(i=0; i<b.length; i++){
if (i%2==0){
string = string.replace( string[b[i]],pre_val)
}
if (i%2==1){
string = string.replace(string[b[i]],post_val)
}
}
return string
}
给出的输入是:
console.log(replaceChar('Baddy',2))
首选输出是:
Baday
我得到的是:
Baady
string = string.replace( string[b[i]],pre_val)
=> 上述语句中 b[i] 的值为 3,因此 string[3] 应替换为 a(先前的值),输出应为 Baday。不知道哪里出了问题。
由于您想替换某个索引处的字符并且您正在进行多次替换(可能),您可以使用数组代替(暂时):
let tmp = string.split(''); //from string into array
for(let i = 0; i<b.length; i++){
if (i%2==0){
tmp[b[i]] = pre_val;
}
if (i%2==1){
tmp[b[i]] = post_val;
}
}
return tmp.join('') //back into a string
此外,您需要正确声明您的其他变量。
let a = string[idx]
let b = []
let pre_val = string[idx - 1]
let post_val = string[idx + 1]
我的代码有一个指向字符串中字符的索引值,我必须用前一个值和下一个值交替替换该字符的所有实例,给定索引字符的值除外。下面是我实现这个的代码:
function replaceChar(string,idx){
a = string[idx]
b= []
pre_val = string[idx - 1]
post_val = string[idx + 1]
for(let i=0; i< string.length ; i++){
if(i==idx){
continue
}
if (string[i]===a){
b.push(i)
}
}
for(i=0; i<b.length; i++){
if (i%2==0){
string = string.replace( string[b[i]],pre_val)
}
if (i%2==1){
string = string.replace(string[b[i]],post_val)
}
}
return string
}
给出的输入是:
console.log(replaceChar('Baddy',2))
首选输出是:
Baday
我得到的是:
Baady
string = string.replace( string[b[i]],pre_val)
=> 上述语句中 b[i] 的值为 3,因此 string[3] 应替换为 a(先前的值),输出应为 Baday。不知道哪里出了问题。
由于您想替换某个索引处的字符并且您正在进行多次替换(可能),您可以使用数组代替(暂时):
let tmp = string.split(''); //from string into array
for(let i = 0; i<b.length; i++){
if (i%2==0){
tmp[b[i]] = pre_val;
}
if (i%2==1){
tmp[b[i]] = post_val;
}
}
return tmp.join('') //back into a string
此外,您需要正确声明您的其他变量。
let a = string[idx]
let b = []
let pre_val = string[idx - 1]
let post_val = string[idx + 1]