JAVASCRIPT ENCOUNTERS ISSUE WITH RANDOM TEXT GENERATION

Utilizing an array of words, we are in the process of generating random text. The goal is to shuffle and combine these words to form new "random sentences". However, we have encountered a minor issue - the addition of "undefined" at the beginning of each paragraph, as well as incorporating random words at the end. Any assistance with this matter would be greatly appreciated.

We aim to ensure that each sentence commences with a capital letter and concludes with a period.

Note: While the snippet does not produce randomized text, it functions correctly in the .js file.

var buttonElem = document.getElementById("DoAgain");
buttonElem.addEventListener('click', makeNewString);


var str = "Lorem ipsum dolor sit amet consectetur adipiscing elit Nullam malesuada ac nulla id interdum Nam volutpat nulla id neque scelerisque ut imperdiet tellus mattis Aliquam a consectetur felis Praesent at eros lorem Nunc id pretium lacus sed porta ex Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas Maecenas mollis posuere auctor Aenean ultrices eleifend diam mattis varius tellus convallis sagittis Donec ut lacus vel nulla laoreet mollis Quisque faucibus nunc at nisi ullamcorper facilisis";

var mixedRes = [];
var currentPosition = 0;
var newString = "";


function addTag(){
newString = "<p>" + str + "</p>";
}


function makeNewString() {
    
    str=str.toLocaleLowerCase();
    var res = str.split(" ");
     mixedRes = shuffle(res);
   
  
      for(var i=0; i<mixedRes.length; i++)
    {
        newString += mixedRes[i] + " ";
    }
  
    newString+=makeSentence(6);

        document.getElementById("demo0").innerHTML = newString;    
}

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  while (0 !== currentIndex) {

    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function capitalise(word){
return (word.charAt(0).toUpperCase()+word.slice(1));
}

function makeSentence(slenght){
var slength=randomNumber(5,10);
   
    var upperCaseLetter = "";
    upperCaseLetter=mixedRes[currentPosition].charAt(0).toUpperCase();

for (var i=currentPosition+1; i<currentPosition+slength;i++){
newString+=mixedRes[i]+"";
}

currentPosition+=slength;
    
    var finalString=upperCaseLetter+newString+".";

   document.getElementById("demo1").innerHTML = finalString;
}

function makeParagraph(){
newString+="\n";
}

function randomNumber(a,b) {
    return Math.round(Math.random()*(b-a)+parseInt(a));
}
<p id="demo0">Lorem ipsum dolor sit amet consectetur adipiscing elit Nullam malesuada ac nulla id interdum Nam volutpat nulla id neque scelerisque ut imperdiet tellus mattis Aliquam a consectetur felis Praesent at eros lorem Nunc id pretium lacus sed porta ex Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas Maecenas mollis posuere auctor Aenean ultrices eleifend diam mattis varius tellus convallis sagittis Donec ut lacus vel nulla laoreet mollis Quisque faucibus nunc at nisi ullamcorper facilisis.</p>

<button class="button1" id="DoAgain"> DO IT AGAIN</button>

Answer №1

When modifying your code, make this adjustment:

document.getElementById("result").innerHTML = newString;

to:

document.getElementById("output").innerHTML = newString;

Answer №2

You have newString+=makeSentence(6); in your code, but makeSentence() doesn't have a return statement, so it returns undefined. I guess it's supposed to return finalString instead of assigning it to .innerHTML of an element that doesn't exist.

var buttonElem = document.getElementById("DoAgain");
buttonElem.addEventListener('click', makeNewString);


var str = "Lorem ipsum dolor sit amet consectetur adipiscing elit Nullam malesuada ac nulla id interdum Nam volutpat nulla id neque scelerisque ut imperdiet tellus mattis Aliquam a consectetur felis Praesent at eros lorem Nunc id pretium lacus sed porta ex Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas Maecenas mollis posuere auctor Aenean ultrices eleifend diam mattis varius tellus convallis sagittis Donec ut lacus vel nulla laoreet mollis Quisque faucibus nunc at nisi ullamcorper facilisis";

var mixedRes = [];

var currentPosition = 0;

var newString = "";

function addTag() {
  newString = "<p>" + str + "</p>";
}

function makeNewString() {

  str = str.toLocaleLowerCase();
  var res = str.split(" ");
  mixedRes = shuffle(res);
  newString += mixedRes.join(" ") + " ";

  newString += makeSentence(6);

  document.getElementById("demo0").innerHTML = newString;
}

function shuffle(array) {
  var currentIndex = array.length,
    temporaryValue, randomIndex;

  while (0 !== currentIndex) {

    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

function capitalise(word) {
  return (word.charAt(0).toUpperCase() + word.slice(1));
}

function makeSentence(slenght) {
  var slength = randomNumber(5, 10);

  var upperCaseLetter = "";
  upperCaseLetter = mixedRes[currentPosition].charAt(0).toUpperCase();

  for (var i = currentPosition + 1; i < currentPosition + slength; i++) {
    newString += mixedRes[i] + "";
  }

  currentPosition += slength;

  var finalString = upperCaseLetter + newString + ".";

  return finalString;
}

function makeParagraph() {
  newString += "/n";
}

function randomNumber(a, b) {
  return Math.round(Math.random() * (b - a) + parseInt(a));
}
<p id="demo0">Lorem ipsum dolor sit amet consectetur adipiscing elit Nullam malesuada ac nulla id interdum Nam volutpat nulla id neque scelerisque ut imperdiet tellus mattis Aliquam a consectetur felis Praesent at eros lorem Nunc id pretium lacus sed porta ex Pellentesque
  habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas Maecenas mollis posuere auctor Aenean ultrices eleifend diam mattis varius tellus convallis sagittis Donec ut lacus vel nulla laoreet mollis Quisque faucibus nunc at nisi
  ullamcorper facilisis.</p>

<button class="button1" id="DoAgain"> DO IT AGAIN</button>

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

Node.JS executes Sandbox within a RESTful service environment

Utilizing the Node Restify Module to develop a REST service that accepts POST requests. Inside the service, I am attempting to create a Sandboxed process using the Node Sandbox module in order to execute dynamically inserted JavaScript without impacting th ...

Creating a Form with a Custom Format in AngularJS

Just starting out with AngularJS and currently working with ACTIVITI. I'm looking to create a form in a specific structure where each response follows this format: { "taskId" : "5", "properties" : [ { "id" : "room", ...

React - error caused by an invalid hook call. Uncaught Error: React encountered a minified error with code #

My goal is to incorporate the micro-frontend concept by implementing various react apps. Container Header Dashboard All three are separate applications. I intend to utilize the Header and Dashboard apps within the Container app. For the Header app, it& ...

Strings that automatically adjust to fit the content from a JSON object

I have a JSON object with a long string that I want to display. The string looks like this: "String":"<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever si ...

Highchart displays text centrally on legend hover

I am struggling with the code provided here. My goal is to make text appear in the center of the donut chart when hovering over the legend. Similar to how it works when hovering over a single piece of the donut chart. var chart = new Highcharts.Chart ...

What is the best method for storing a Google Analytics object in a $_SESSION variable when transitioning between PHP scripts to avoid encountering a non-object error

Currently in the process of developing a web application that integrates with the Google Analytics API, however encountering challenges when it comes to implementation. The user is given the option to choose their profile from three interconnected drop-do ...

Choose the minimum price from the JSON response of the API

I have made an AJAX request to an API and received the following JSON response below. I am trying to extract the lowest 'MinPrice' from the 'Quotes' data but finding it challenging to determine the best approach. One method I am consid ...

Overlap of columns within a nested flexbox arrangement

While working with React and Styled Components, I encountered a problem of elements overlapping each other: https://i.stack.imgur.com/RuCYu.png There are a few instances of overlap, including: The padding below the <ul> element is colliding with ...

Tips for sending a JSON object from a PHP file to a JavaScript variable

Forgive me if this has already been discussed in a previous post, I have not been able to find the answer. My PHP page generates an array in JSON format: [{ "chemical":"Corrosion_Inhibitor", "TargetDose":81, "AppliedDose":26, "ppbbl":"$0.97" ...

A checkbox placed within an anchor tag

Here is some code that I have: <a href class="dropdown-toggle"> <input type="checkbox" ng-model="test.checked"> <span class="fa fa-angle-down"></span> </a> When I click on the above code, I want the chec ...

Can you provide guidance on utilizing OneNote JavaScript APIs to interpret indented paragraphs within OneNote?

I keep a notebook that contains the following entries: https://i.stack.imgur.com/MLdO0.png For information on OneNote APIs, you can refer to this link (paragraph class selected already) https://learn.microsoft.com/en-us/javascript/api/onenote/onenote.p ...

The req.ip in Express appears to alternate between displaying my local machine address as ::ffff:127.0.0.1 and ::1 in an unpredictable manner

Simply put, the title sums it up. I've spent the last few hours working on a middleware function that uses cookies for authentication, like so: const authRoute = async (req, res, next) => { console.log(req.ip); // additional logic here ...

Master the art of string slicing in JavaScript with these simple steps

I am attempting to utilize the slice function to remove the first three characters of a string within a JSON object. $(document).ready(function() { $.ajaxSetup({ cache: false }); setInterval(function() { $.getJSON("IOCounter.html", functio ...

The constricted styles are causing the whole page to bounce (scroll) up and down

On my SPA frontend, I have a parent div with a height of 580 containing 9 smaller divs (about 190px in height each). The parent div has an overflow set to hidden so that only 3 elements are visible at one time. Every 5 seconds, I change the styles by addin ...

What is the best way to send data from ajax to a django view?

I have a script for ajax that retrieves the public key and sends other details to the Stripe server for payment. However, I am struggling with sending the dynamic value of the price to item_line. fetch("/config/") .then((result) => { return re ...

Refreshing data and manipulating arrays using AngularJS

Currently, I am developing an application utilizing AngularJS and LocalStorage. I've encountered a challenge that seems a bit too intricate for me to handle. The app involves managing lists of people with the ability to add arrays of names. The proce ...

Is it possible to have a div automatically scroll when hovered over, while also hiding the scroll bar specifically for that div?

Is there a way to autoscroll a specific element onmouseover or via an image map while also hiding the scrollbars for that div? I seem to be struggling with this task despite weeks of learning javascript and not being able to find the right solution online. ...

Ensure that all form fields are completed and accurate before the Stripe payment modal is displayed

I've encountered an issue where the stripe payment modal appears before my form validation is complete. I am using the jQuery validation plugin for this purpose. I attempted to integrate the Stripe code within the submitHandler function, but it did no ...

Detecting changes to DOM elements without using jQueryResponding to DOM element

Suppose I have the following HTML structure: <div id='content'></div> I want to receive an alert when there are height mutations on this element. I thought about using the MutationObserver class for this, but I encountered a specifi ...

Break down the text of a paragraph into separate words, placing each word within its own span element, and then add animations

I am facing an issue with my paragraph element that has the display property set to hidden. I have split each word of the paragraph and placed them inside individual span elements. My goal is to create an effect where each word comes from different locatio ...