首页 > 解决方案 > 在javascript中最初删除子字符串后,如何确保将子字符串放回字符串的正确索引?

问题描述

我有一个如下所示的字符串

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'."

如何确保在适当的位置替换特殊字符并取回原始字符串?

标签: javascriptreplaceindexof

解决方案


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

// !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());


推荐阅读