Unpredictable term pulled from the Javascript/Ajax content

Can someone help me figure out how to randomly select just one word from a block of text using JavaScript?

Here's the code I've been working with:

function someFunction() {

    // need help here

var word;

$.ajax({
     async: false,
     type: 'GET',
     url: link,
     success: function(data) {
        word = getWord(data); // retrieve random word from data
     }
});

}



function getWord(text) {

// could anyone assist me with this?

}

I believe this should be a straightforward fix. Appreciate any assistance!

Answer №1

For a similar solution, check out http://jsfiddle.net/Y9bCG/

alert(getWord("there is a book there"));
function getWord(data)
{   
    var wordArray=data.split(' ');    

    var maxIndex = wordArray.length-1;
    var randomIndex = (Math.floor(Math.random() * (maxIndex + 1)));
    return wordArray[randomIndex];
}

Answer №2

Here's a code snippet that does something similar:

const getRandomWord = (text) => {
    const words = text.split(' ');
    return words[Math.floor(Math.random() * words.length)];
};

function generateRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

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

Reorganizing array sequence within a sortable list

I'm currently working with the react-beautiful-dnd module to build a draggable list. The backend data I receive is arranged according to the sequence field. Once an item is dragged and dropped, I utilize the reorder function to generate a new list. Ho ...

The variable remains undefined, despite the fact that the code executes correctly in a different location

I'm currently working on a multiplayer game in three js and integrating socket.io for real-time communication. I have all the player characters stored in an array called players on the server side. When each client connects, I send them the list of p ...

Looking to decrease Cumulative Layout Shift (CLS) on the NextJS website for enhanced performance

I have chosen to use NextJS with Mantine for my website development. Utilizing createStyles, I have added custom stylings and incorporated various mantine components into the design. After deploying the site on Vercel, I discovered that all performance me ...

JavaScript namespace problems

Although I am using a namespace, the function name is getting mixed up. When I call nwFunc.callMe() or $.Test1.callTest(), it ends up executing _testFunction() from the doOneThing instead of the expected _testFunction() in the $.Test1 API. How can I correc ...

The res.send() function is being executed prior to the async function being called in express.js

My current project involves creating an API that returns epoch time. I am using an express.js server for this, but the issue arises when the res.send() function is called before the getTimeStamp() function finishes executing. I tried looking up a solution ...

Click to shift the div downwards

Currently, I have a piece of javascript applied to a div that directs the user to a specific link: <div style="cursor:pointer;" onclick="location.href='http://www.test.com';"> I am wondering if there is a way to add an effect where, upon ...

What is the best way to transfer a variable from a Node.js Express server to an EJS HTML file in order to toggle alert visibility?

Hello, I am currently facing a challenge in sending a variable from my app.js file to my ejs HTML file in order to toggle the display of an alert. Here is what the relevant part of my app.js code looks like: view image description here Initially, I attem ...

Creating visualizations with Django and Highcharts while maintaining a DRY codebase

Currently, I am in the process of developing a server dashboard that heavily relies on graphs and charts. The backend is powered by Django, while we are using Highcharts/Highstock for the graphical representation (though we are also considering D3 dependi ...

When utilizing Angular, be cautious of encountering an "undefined" error when attempting to add a JavaScript function

I have a good understanding of Javascript and Jquery, but I am relatively new to Angular. Although I've used jquery with angular in the past without any issues, the application I recently inherited is causing me quite a bit of trouble. Whenever I cli ...

Securing client-side code with AngularJS for enhanced security

It's a known fact that once browsers have downloaded frontend files, there's no way to hide code from the client. However, I've heard that clients can debug JavaScript code, add breakpoints, skip code lines (especially security checks), and ...

Adjusting image width using jQuery

I have been experimenting with creating a Webgl hover effect for an image. The effect works well, but now I am trying to specify a width for the image within jQuery. new hoverEffect({ parent: document.querySelector('.ticket'), intensity1: 0. ...

computational method for organizing balls in a circular formation

I need help arranging 10 spheres in a ring using code. So far, this is what I have, but it's not working as expected. const sphereGeometry = new THREE.SphereGeometry(300, 20, 20); const sphereMaterial = new THREE.MeshLambertM ...

The Push Over Menu is malfunctioning and not functioning properly

I am facing an issue with pushing my menu along with the content to the right. The JS code I have is not working as expected. When I click on <div class="menu-btn toggle"></div>, the menu does not trigger. Can someone help me understand why thi ...

Can a library be developed that works with both Java and JavaScript/TypeScript?

I specialize in Angular development. Our front- and backend both contain specialized calculation methods that work like magic. Although the classes are the same, any bugs found in the calculations have to be fixed separately in two different projects. Is ...

The event handling mechanism in React JS for elements coming into view

Can someone please guide me on implementing the inview event in React JS? I want to achieve something like this: <div inview={handleInView}></div> I specifically need to add it to the Footer section so I can dynamically load more news a ...

The array in Ajax is consistently limited to a size of 1

Having an issue with retrieving the value of checked checkboxes using a function. When alerting the values in JavaScript, it shows '1,2,3' which is correct. However, when retrieving it from PHP, the array size is always 1. HTML CODE: function ...

The React-Leaflet curly braces positioned on the top left corner of the map

Is there a way to remove the curly braces and symbols near the zoom pane when the map is too far? https://i.stack.imgur.com/eGQCd.png p.s. Here is some provided code for reference: p.s. 2 - I have noticed that adding a condition like {condition1 &a ...

Issue with Node.js Stream - Repeated attempts to call stream functions on the same file are not being successful

When a POST request with multipart/form-data hits my server, I extract the file contents from the request. The file is read using streams, passed to cvsParser, then to a custom Transform function that fetches the resource via http (utilizing got) and comp ...

What could be preventing a successful POST request with data when making an ajax call?

My goal is to send data using a POST request in client-side code. However, when the request reaches the controller methods, I am unable to retrieve the sent data. Here is the client-side code snippet: function AddUser() { var user = { ...

Is it possible to connect to a Node server from outside the network if the application is only listening on 'localhost'?

When utilizing the Express framework and we implement app.listen(port), the app will be located at localhost:port/ On a local machine, it is clear how to access this address using a local browser running on the same machine. Even clients within the same n ...