JavaScript - 如何随机播放字符串中的字符并跳过某些字符(S)

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

我是一个 javascript 初学者,我遇到了一个问题。我有一个 javascript 函数来打乱字符串中的字符,从而保持单词长度和空格就像原始句子一样。

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

String.prototype.shuffle = function () {
  // pass to shuffleArray an array of all non-whitespace characters:
  const randomChars = shuffleArray([...this.replace(/\s+/g, '')]);
  let index = 0;
  // `\S` matches any non-whitespace character:
  return this.replace(/\S/g, () => randomChars[index++]);
}

console.log(
  `The keys are under the mat`
  .shuffle()
);

我想添加的是向函数添加一个具有定义字母的变量,该变量应该在随机播放过程中跳过。现在我们有了,即:

  • 原字符串:

钥匙在垫子下面

  • 现在打乱的字符串看起来像:

atd meey eke nTshr hau ert

  • 以及我想要的: 我想定义字符,例如:[hr],这些字母应保持“冻结”在其位置,而不是由随机播放功能处理:

最终结果:

ahd meey ere nTshr ahu ekt

javascript string character scramble
2个回答
0
投票

我能想到的最佳解决方案如下:

  1. 将所有不需要替换的字母存储在数组中。
  2. 迭代原始字符串,用数组中的随机字符替换每个字符,只要您要替换的字符不是(在您的情况下):['h','r']。

有很多方法可以解决这个问题,但使其高效取决于一系列因素,例如特定的输入字符串、它的长度以及排除数组中的字符数。

我会考虑使用 .split() 方法,如下所示:w3schools .split()

希望这有帮助。


0
投票

你可以取一串剩下的字符,构建两个正则表达式进行收集和替换。

function shuffleArray(array) {
    for (let i = array.length - 1; i; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

String.prototype.shuffle = function (keep = '') {
    keep += '\\s';
    const
        chars = this.replace(new RegExp(`[${keep}]`, 'gi'), ''),
        randomChars = shuffleArray([...chars]);
   
    let index = 0;
    return this.replace(new RegExp(`[^${keep}]`, 'gi'), () => randomChars[index++]);
};

console.log('The keys are under the mat');
console.log('The keys are under the mat'.shuffle());
console.log('The keys are under the mat'.shuffle('hr'));

© www.soinside.com 2019 - 2024. All rights reserved.