【问题标题】:Typo Generator Javascript错别字生成器 Javascript
【发布时间】:2022-11-18 19:15:16
【问题描述】:

我创建此代码是为了在页面上的所有单词中创建拼写错误。该代码会打乱单词内部的字母,但会保留第一个和最后一个字符。但是,我如何忽略像“。”这样的标点符号? "(" "," ")" 作为第一个和/或最后一个字符?

let words = document.body.innerText.split(" ");
let scrambled = "";
for (var i = 0; i < words.length; i++) {
  var word = words[i];
  var letters = word.split("");
  var first = letters[0];
  var last = letters[letters.length - 1];
  for (var j = 1; j < letters.length - 1; j++) {
    var letter = letters[j];
    var index = Math.floor(Math.random() * (letters.length - 2)) + 1;
    var temp = letters[index];
    letters[index] = letter;
    letters[j] = temp;
  }
  letters[0] = first;
  letters[letters.length - 1] = last;
  scrambled += letters.join("") + " ";
}
document.body.innerText = scrambled;
I created this code to create typo's within all words on a page. The code scrambles the letters in the interior of the word, however, it leaves the first and last character. But, how do I ignore punctuation like "." "(" "," ")" that acts as the first
and/or last character?

【问题讨论】:

  • 我给你做了一个 sn-p。我不得不猜测单词并争先恐后。请添加相关的html、CSS和可能的框架

标签: javascript


【解决方案1】:

您可以使用匹配单词最大可能内部部分的正则表达式,要求这些部分两边都被一个字母包围,然后将这些部分打乱:

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

const scramble = text =>
    text.replace(/(?<=w)S+(?=w)/g, s => shuffle([...s]).join(""));

document.body.innerText = scramble(document.body.innerText);
I created this code to create typo's within all words on a page. The code scrambles the letters in the interior of the word, however, it leaves the first and last character. But, how do I ignore punctuation like "." "(" "," ")" that acts as the first
and/or last character?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    相关资源
    最近更新 更多