我是一个脚本初学者,我遇到了一个问题.我有一个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(
  ` keys 在垫子下面`
  .shuffle()
);

我想要添加的是向函数添加一个定义了字母的变量,该变量应该在洗牌过程中跳过.现在我们有了,即:

  • 原始字符串:

keys 在垫子下面

  • 现在,混洗后的字符串如下所示:

ATD meey eke nTshr Hau ERT

  • 我想要的是: 我想定义字符,例如:[hr],这些字母应该保持在它们的位置上,而不是被Shuffle函数处理:

最终结果:

hd meey ere nTshr ahu ekt

推荐答案

我相信这段代码实现了您想要的功能:

function shuffleString(string, fixed) {
    let result = '';
    const allChars = Array.from(string);
    const fixedChars = Array.from(fixed); 
    fixedChars.push(" "); // Consider the blank space as a fixed character, as you wish to maintain the separation on the string
    const singleChars = Array.from(string).filter(char => !fixedChars.includes(char));

    allChars.forEach((char) => { 
        if (fixedChars.includes(char)) { // If the sting is fixed, just add it
            result += char;
        } else { // If string is not fixed, get a random one
            const randomPosition = Math.floor(Math.random() * (singleChars.length));
            result += singleChars[randomPosition];
            singleChars.splice(randomPosition, 1); // Remove from the options array, since it should not be selected more than once
        }
    });
    
    return result;
}

console.log(shuffleString('this is a test', 'et'));

它是O(N),n是文本中的字母数. 希望它能帮上忙!

Javascript相关问答推荐

如何判断属于多个元素的属性是否具有多个值之一

单击更新页面的按钮后,页面刷新;测试/断言超时,有两个标题,但没有一个标题

使用续集和下拉栏显示模型属性

在vercel throws上部署带有gunjs的sveltekit应用无法找到模块./' lib/文本编码'

react—router v6:路由没有路径

如何在不创建新键的情况下动态更改 map 中的项目?

康威的生活游戏规则在我的Javascript版本中不起作用.''我做错了什么?

当运行d3示例代码时,没有显示任何内容

在Three JS中看不到补间不透明度更改效果

更改预请求脚本中重用的JSON主体变量- Postman

第三方包不需要NODE_MODULES文件夹就可以工作吗?

使用VUE和SCSS的数字滚动动画(&;内容生成)

Nextjs 13.4 Next-Auth 4.2登录(&Quot;凭据&,{});不工作

使用插件构建包含chart.js提供程序的Angular 库?

AJAX POST在控制器中返回空(ASP.NET MVC)

令牌JWT未过期

Google脚本数组映射函数横向输出

如何使用Cypress在IFRAME中打字

Django模板中未加载JavaScript函数

如何在preLoad()中自定义p5.js默认加载动画?