在javascript中,如何确保字符串的子串在被删除后被放回正确的索引处?

问题描述 投票:0回答:1

我有一个字符串,它看起来像下面

query = "I learned to =play the 'Ukulele' in 'Lebanon'."

如你所见,它有一些特殊的字符,如 =, ' 中,我想先将其删除。

然而我删除的任何东西最终都要放回去。所以在删除之前,我必须记住这些特殊字符每次出现的索引位置。所以我写了一段代码来存储映射信息,其中包含字符和它们的多个索引。它是这样的

specialCharIndexMapping {
  ',': [],
  "'": [ 23, 31, 36, 44 ],
  '"': [],
  '=': [ 13 ],
  '>': [],
  '<': []
}

如你所见,单引 ' 在指数23、31、26、44出现过,并等于 = 已经出现在索引13处。

现在我从字符串中删除特殊字符

query = query.replace(/"/g,"").replace(/'/g,"").replace(/=/g,"").replace(/>/g,"").replace(/</g,"").replace(/,/g,"");

所以现在我的查询结果如下

query = I learned to play the Ukulele in Lebanon.

现在我需要根据索引信息将这些特殊字符放回我的字符串中。所以我是这样做的

for (char in specialCharIndexMapping) {
        if(specialCharIndexMapping[char] !== []) {
            charIndices = specialCharIndexMapping[char]
            for(i=0; i<charIndices.length; i++) {
                index = charIndices[i]
                //query = query.substr(0, index) + char + query.substr(index);
                query = query.slice(0, index) + char + query.slice(index);
            }
        }
    }
    console.log(query)
}

但这些字符被放回了错误的位置。这就是我最后的字符串的样子

query = "I learned to =play the U'kulele 'in L'ebanon.'"

花了一些时间,我意识到这可能是由于引入了新的字符,字符串被移动了。所以后续的索引将不成立。所以我试着做了下面的事情

for (char in specialCharIndexMapping) {
        if(specialCharIndexMapping[char] !== []) {
            charIndices = specialCharIndexMapping[char]
            for(i=0; i<charIndices.length; i++) {
                if (i==0) {
                  index = charIndices[i]
                }
                else {
                    index = charIndices[i] -1
                }
                //query = query.substr(0, index) + char + query.substr(index);
                query = query.slice(0, index) + char + query.slice(index);
            }
        }
    }
    console.log(query)
}

除了第一次替换外,我基本上一直把索引位置减少1。这确实使它更接近原始字符串,但它仍然是错误的。这就是现在的样子

query = "I learned to =play the U'kulele' in 'Lebanon'."

我如何确保特殊字符在适当的地方被替换,并得到原始字符串?

javascript replace indexof
1个回答
1
投票

我做了代码,希望对你有帮助!关键因素是转换为一个数组,它让你比字符串更好地操纵它。

// !WARNING: This code uses ES6 (ECMA2015+) syntax
const query = "I learned to =play the 'Ukulele' in 'Lebanon'.";
const charToRemove = [',', "'", '"', '=', '>', '<'];

const foundPositions = []
// Loop over all letters and save their respective position and their character
const cleanedQuery = query.split('').map((char, index) => {
  if (charToRemove.includes(char)) {
    foundPositions.push([index, char]);
    // Return an empty string to remove the character
    return '';
  } else {
    return char;
  }
}).join('');

console.log('cleanedQuery', cleanedQuery);
console.log("savedPositions", foundPositions);

// Loop over found characters to put them back into place
const rebuiltQuery = foundPositions.reduce((acc, pair) => {
  const [
    index,
    char
  ] = pair;
  acc.splice(index, 0, char);
  return acc;
}, cleanedQuery.split('')).join('');

console.log("originalQuery", rebuiltQuery);
console.log('query and originalQuery are the same:', (query === rebuiltQuery).toString());
© www.soinside.com 2019 - 2024. All rights reserved.