您可以创建一个字符串,其中包含需要保留的所有字符,并基于此构建两个正则表达式,分别用于提取需替换的字符和进行替换操作。
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>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 (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')); // 保留'h'和'r',其余字符打乱</code></pre>
</div>
</div>
</p>