【问题标题】:Why am I getting the wrong output while using str.replace()?为什么我在使用 str.replace() 时得到错误的输出?
【发布时间】:2021-11-11 23:06:15
【问题描述】:

我的代码有一个索引值,它指向字符串中的一个字符,我必须用前一个值和下一个值替换该字符的所有实例,但给定索引字符的值除外。下面是我实现这个的代码:

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。不知道出了什么问题。

【问题讨论】:

  • string.replace() 替换string[b[i]] 的第一个匹配项。如果有较早的匹配,它不会替换索引i 处的匹配。
  • 嗨,我不确定以前的值是什么? string[3] 不是直接转到字符串中的第 4 个值吗? b 只有 [3] 作为元素,所以它是 string[3] right
  • 如果string 中有同一个字符的多个副本,则不会。
  • 如果string = ="aabbb"string[3] == "b",那么string.replace(string[3], something) 将替换string[2] 处的b,而不是string[3] 处的b
  • 是的,现在你明白了。

标签: javascript string list replace


【解决方案1】:

由于您想替换某个索引处的字符并且您正在执行多次替换(可能),您可以使用数组来代替(暂时):

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]

【讨论】:

    猜你喜欢
    • 2012-04-26
    • 1970-01-01
    • 2014-01-06
    • 2012-12-27
    • 2019-01-25
    • 2021-11-18
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多