Javascript Tool for Generating Typos

My goal with this code was to introduce typos into all words on a page. The script shuffles the letters inside each word, while keeping the first and last characters intact. However, I encountered an issue with punctuation marks such as ".", "(", ",", ")" that sometimes act as the first or last character of a word.

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?

Answer №1

To add typos to words on a page, you can employ a regular expression that identifies the maximum inner parts of words surrounded by letters on both sides. After identifying these parts, you can scramble them using the following code:

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);
This script generates typos by scrambling the interior letters of words on a page while preserving the first and last characters. To exclude punctuation marks like ".", "(", ",", ")" from being considered as the first or last character, additional logic needs to be added.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...

What is the best way to incorporate a changing variable within an htmx request?

One of the endpoints in my site requires an ID to be passed as a parameter. For example: mysite.com/product/{id}?limit=5 I'm wondering how to pass the 'id' variable in the hx-get attribute. I can utilize AlpineJS or vanilla JS for this tas ...

Tips for Allowing Multiple Exports in a Vue 3 Single File Component

I am currently working on a Vue3 Single File Component for a customized list. Within this single file component, my objective is to export the main default Vue component along with an enum that declares the type of list it represents: child: <template& ...

Retrieving PHP form values using JQuery

How can I transfer a form input value from a PHP file to a JavaScript file? Here is the code I am currently using: <html> <head> <meta charset = "UTF-8"> <title> Search Customer by Field </title> <s ...

Is it feasible to create a translucent overlay that sits atop another element without hindering or intercepting mouse clicks using CSS and JavaScript?

I'm looking to overlay one layer on top of another without capturing input. My aim is to place a PNG image over my webpage in order to achieve a filter-like effect. The issue I'm facing is that when the overlay is in place, the text becomes uns ...

I am having trouble getting my AngularJS client to properly consume the RESTful call

As I venture into the world of AngularJS and attempt to work with a RESTful service, I am encountering a challenge. Upon making a REST call to http://localhost:8080/application/webapi/myApp/, I receive the following JSON response: { "content": "Hel ...

What is the best way to accurately determine an element's location after scrolling to it?

I'm currently working on pinpointing the location of a specific element on a webpage once it has been scrolled to using JavaScript. Queries: How can I precisely determine the position of an element post-scroll? What are some common errors or extra st ...

Displaying a div component in React and Typescript upon clicking an element

I've been working on a to-do list project using React and TypeScript. In order to display my completed tasks, I have added a "done" button to the DOM that triggers a function when clicked. Initially, I attempted to use a useState hook in the function ...

I am getting a HTTP 405 error indicating that the method is not allowed, and it appears to

In my Javascript program, I requested this URL using the library epson-2.6.0.js, which is the Epson SDK for JavaScript specifically designed for thermal printers. My target device is a TM U220 connected via ethernet. GET XHR http://192.168.199.15:8008/soc ...

Swap out a paragraph with a city name fetched from a JSON file

While working on a weather app, I encountered an issue. The app needs to automatically detect the user's location and display the appropriate temperature along with the city name. I have been trying to fetch data from JSON to replace the placeholder t ...

Automatically refresh the Redux state in ReactJS at regular intervals to ensure the data is always up-to

I'm trying to implement a solution for running a background process in my React App, which will periodically call a backend API and update the redux state. The app is quite large with numerous components, so I need a global approach that doesn't ...

It is not possible to include external JavaScript in a Vue.js web page

Trying to integrate a Google Translate widget onto my webpage has been a bit challenging. Initially, when I added it to a normal webpage, it worked smoothly using the following code: <div class="google_translate" id="google_translate_element"></d ...

What is preventing the click function on a dynamically created button from being executed in jQuery?

Take a look at this jsFiddle where I illustrate my issue. Whenever I click on the "Add an ingredient" button, the button click event is triggered. My issue arises when I click on the "Create a subtitle" button because it dynamically creates "Add an ingredi ...

Encountering issues while trying to duplicate react-table CodeSandbox: API error when using localhost

Trying to implement this CodeSandbox project into my own project has been challenging. On navigating to the Example component, a 404 error pops up: Error: Request failed with status code 404. The API is targeting this endpoint: http://localhost:3000/api/pr ...

Issue: Unable to access 'filter' property of null object

I've been working on a small react dropdown task and it's running smoothly in Google Chrome. However, I encountered an error when testing it on MS Explorer. Even after deploying it on a live server, the issue persisted. The specific error message ...

Three.js: Comparing the Process of Updating Geometries with Replacing Them

In my current project, I have a complex scene filled with objects created using the ExtrudeGeometry method. These objects need to be updated every frame, with the extrusion shape and amount constantly changing. The shapes are generated using d3's voro ...

The output of server.address() method in Node.js is ::

My memory serves me right, a few days back it was showing "localhost". I'm puzzled as to what altered server.address().address to now return double colons (::). According to my research, it seems to be returning an IPv6 address (::) because it's ...

Error encountered: Unexpected character 'u' found at the start of JSON parsing. Position 0

Looking for guidance on writing jest test cases for a submit function that involves JSON.parse. The code and test case are provided below. handleFormSubmit = (e) => { e.preventDefault(); let requestData = JSON.parse ...

Surprising outcome of Vue

As a newcomer to vue.js, I am struggling with a side effect issue in a computed property. The unexpected side effect error is popping up when running the code below, and ESlint is pointing it out in the console. I understand the concept of side effects, bu ...

Strange jQuery Bug

Previously, the code on my website was functioning correctly: $("#usr").load("somepage.php",{var1:var1,var2:var2}); However, after making changes to the navigation bar code, jQuery started behaving oddly. The first issue that arose was with this line: v ...