javascript 使用.replace只替换第一个字符

jdgnovmf  于 2023-01-24  发布在  Java
关注(0)|答案(1)|浏览(170)

我在一门课程中纠结于这段代码--它应该只擦除每个字符的第一个示例,但是我的循环擦除了所有示例。我想在测试后从toerase中删除示例,然后在运行后重建,但似乎过于复杂。我如何使用内置的替换函数来解决这个问题?

disappearString = (myString, toErase) => {
    // Place your code here
    
    //let to earase an array of string to disappear
    var toErase = stringToDisappear.split('');

    //toErase = toErase.join(||');//join array with ||(or) didn't work - binned this idea

    //console.log (toErase); //checking its come as an array

        let result = ""; //define result as empty
    //loop to erase each instance - but for f**s sake I don't want to do that, just remove the first instance"!
      for (let i = 0; i < myString.length; i++) {
        let letter = myString[i]; //declare letter
        if (!toErase.includes(letter) ) { //check if letter is the same as any of toerase
          result += myString[i]; //if letter is not in toerase print it.
      
        }
      };
      return result;
    };



// DO NOT EDIT BELOW THIS LINE
let testStrings = [
    "the quick brown fox jumps over the lazy dog",
    "hello world",
    "software engineering is fun",
    "i like javascript",
    "clown case",
    "rhythms"
]

let stringToDisappear = "aeiou"

let correctStrings = [
    "th qck brwn fox jumps over the lzy dog",
    "hll world",
    "sftwr engneering is fn",
    " lik jvascript",
    "clwn cs",
    "rhythms"
]

for (let strIdx = 0; strIdx < testStrings.length; strIdx++) {
    let test = testStrings[strIdx];
    let correct = correctStrings[strIdx];

    let got = disappearString(test, stringToDisappear);

    if (got == correct) {
        console.log(`${strIdx + 1}: Testing ${test}: Correct!`);
    } else {
        console.log(`${strIdx + 1}: Testing ${test}: Wrong, got ${got}, expected ${correct}`);
    }
}
wh6knrhe

wh6knrhe1#

我不确定是否完全理解,你有一个字符串数组,你有一个字符串,你有一个字符串,你想从字符串数组的每个字符串中,删除字符串中的每个字母,一次,然后使用替换。
如果我对这个问题的理解是正确的:

let testStrings = [
  "the quick brown fox jumps over the lazy dog",
  "hello world",
  "software engineering is fun",
  "i like javascript",
  "clown case",
  "rhythms"
];

const stringToDisappear = "aeiou";
const strAr = stringToDisappear.split('');

for (let i = 0; i < strAr.length; i++) {
  for (let j = 0; j < testStrings.length; j++) {
    testStrings[j] = testStrings[j].replace(strAr[i], '');
  }
}
console.log(testStrings);

相关问题