A special function designed to transform words inputted as a parameter into an array

    function createArray(text){
            var arr = [];
            var word = null;

            for(var i = 0; i<text.length; i++){
                if (word == null) {
                    word = "";

                    if(text[i] != "," && text[i] != " " && text[i] != "." && text[i] != "   "){
                        word += text[i];
                    }
                    else{
                        arr.push(word);
                        word = null;
                    }
                }
            return arr;
        }

var newArray = createArray("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nunc varius urna sed pede. Suspendisse sit amet lacus. Vivamus consectetuer fringilla ligula. Nunc metus lorem, pretium adipiscing, sollicitudin nec, ultrices quis, nulla. Phasellus nec nulla a eros adipiscing ultrices. Nulla fermentum lectus. Pellentesque ac risus eu massa auctor bibendum. Cras vulputate, nisi eget gravida condimentum, nisl justo tincidunt magna, rutrum imperdiet dui justo vel risus. Donec sit amet pede. Etiam facilisis mauris vitae risus. Ut a neque. Suspendisse augue est, elementum nec, lobortis vel, pulvinar vitae, sapien. Curabitur venenatis enim sit amet sapien. Mauris fermentum interdum eros. Mauris feugiat adipiscing nisl. Donec non nunc. Donec ante enim, eg."

for(var i = 0; i<newArray.length;i++){
        document.write(i+ ". "+newArray[i]+"<br />");
    }

I have been working on creating a program that can analyze a long piece of text and identify words that only appear once throughout the entire text. I am still in the process of developing this program, but when I tested it to see if it would display each item in the array correctly, the web browser showed a blank screen. In comparison to this alternate code:

function createArray(text){
        var arr = [];
        var word = "";

        for(var i = 0; i<text.length; i++){
            if(text[i] != "," && text[i] != " "&& text[i] != "." && text[i] != "    "){
                word += text[i];
            }
            else{
                arr.push(word);
                word = "";
            }
        }
        return arr;
    }

for(var i = 0; i<newArray.length;i++){
        document.write(i+ ". "+newArray[i]+"<br />");
    }

which functions properly. However, if a character sequence such as ". "(period + space) appears, the program adds an empty item to the array due to word = "";. I attempted to prevent this by using the type null, as w3schools.com states that "Variables can be emptied by setting the value to null." Nevertheless, using null results in an error. Why is this?

Answer №1

  • Initiate a new string named "phrase" ('')
  • Incrementally add characters to it ('H','He','Hel','Hell','Hello')
  • Phrase completed, so append to an array ('Hello')
  • Reset phrase to empty string ('')
  • Add characters to it one by one ('Wor','Worl','World','World!')

Your goal is to clear the string and start fresh, not set it to null.

Answer №2

If I understand your question correctly, you are looking to convert a string into an array of words. One way to achieve this is by utilizing the String.split method and passing a regular expression as an argument to split. Here's an example:

var wordArray = text.split(/[\W]+/);

The split function above splits the text at every occurrence where the provided regular expression matches one or more non-alphanumeric (or underscore) characters in the text.

The blank screen issue may be occurring because you are using document.write() after the document has already been parsed. This action will overwrite all existing content with a new document. Instead, consider creating an element with an id on the page and updating it like this:

document.getElementById('id_of_element').innerHTML = wordArray.join('<br />');

The join() function is the reverse operation of split, transforming an array into a string.

Check out a live demo on jsFiddle.

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

In need of some guidance with PHP's mysqli_fetch_assoc function

I have searched extensively for a solution to my issue but haven't found one that works for me. My problem lies in determining the end of an associative array created by mysqli_fetch_assoc($result). Here is the code I am using: $query = "SELECT * " . ...

Creating a CSV download feature with ReactJS is simple and incredibly useful. Enable users

Despite searching through various posts on this topic, I have yet to find a solution that addresses my specific issue. I've experimented with different libraries and combinations of them in an attempt to achieve the desired outcome, but so far, I have ...

What is the best way to trigger a JavaScript onclick event for a button that is located within a dropdown menu on an HTML page

I've implemented a feature that resizes the font size within a text area based on the selected font size. It was functioning flawlessly... until I decided to place the font size selection in a drop-down menu, which caused the feature to stop working. ...

AngularJS: Changing color property using toggle when a CSS class is modified

After starting to learn AngularJS, I have been able to find many helpful answers on this forum. However, there is one particular issue that has been causing me frustration. My goal is to dynamically change the color property of an element only when it has ...

When working on a MEAN web application, encountering HTTP responses like 403 or 500 from the Express server can sometimes go unnoticed and not be properly handled in the errorCallback function within

Within my Node web app, there is a situation where an HTTP GET request is sent in one of the Angular controllers. At the same route defined in Express, somewhere in the route logic, an HTTP 500 response (also tried 403 Error) is also being sent. However, i ...

Interpret a variety of date formats using date-fns

Here is a code snippet that I am working with: function checkDate(value: string) { return isBefore( parse(value, 'dd-MM-yyyy', new Date()), sub(new Date(), { days: 1 }) ); } const result = checkDate('31-12-2020'); In the p ...

Using Angular's ng-model Across Multiple Views

Is it possible to use ng-model to gradually build an object across multiple views? For example, in view1 I have <input ng-model='myObject.firstName'> And in view2 I have <input ng-model='myObject.lastName'> And in view3 ...

The margin set in Bootstrap isn't making any difference

I'm currently utilizing bootstrap 4 in my react project, and while the bootstrap components seem to be functional, I am facing an issue where setting margins does not work as expected. Here is a snippet of code from one of my pages: return ( < ...

The Firebase read counts are increasing rapidly, even during times of inactivity

Explaining the issue I'm facing in detail, I recently embarked on developing my first larger project, a project management app using React. Everything was progressing smoothly until I started working on the task addition feature and updating graphs w ...

Hide the button with jQuery Ajax if the variable is deemed acceptable upon submission

I need to figure out how to hide the submit button if the email entered is the same as the one in the database from action.php. Can anyone help me with integrating this functionality into my existing code? <form onsubmit="return submitdata();"> ...

ng-repeat to prevent duplicate items from displaying

I intentionally have duplicates in my array of items and I am looking for a way to hide just one of them when clicked within my ng-repeat. Is there a way to hide only one of the duplicated items on click? I feel like I might be overlooking something, as ...

Sometimes the AngularJS scope is refreshed only intermittently

I am encountering an issue with a list of cards retrieved from an API and displayed in a table using ng-repeat. The problem arises when I attempt to delete a card - sometimes it remains in the view, while other times it disappears as expected after confirm ...

Utilizing Google Maps API to dynamically input destinations in text boxes

Check out my code at this link: I apologize for the inconvenience, but I had some difficulty pasting it directly into this forum. The code is functioning well, however, I need assistance with a particular issue. Currently, the textboxes for start and des ...

Exploring the world of functional programming within nested arrays

I have been shifting towards functional programming over imperative programming recently. Imagine I have a nested array data structure and my goal is to update the values of the innermost arrays. What approach would be most effective? Here is the imperat ...

Encountering installation issues with npm for bcrypt installation due to a

While working on an Express JS project, I encountered issues trying to install the bcrypt module for data authentication. Despite multiple attempts, I kept receiving the same errors. [email protected] install /media/iron/1d6c195f-2350-423c-a3f0-050 ...

Having trouble successfully sending a variable through a JavaScript form

Within my HTML file, I have a form with various input fields and radio buttons that allow users to enter search parameters. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href='https:// ...

The selection elements fail to reset correctly

I'm currently working on an Angular 4 application where I have a form that includes a select element inside a box. <div class="form-group"> <label for="designation">Designation</label> <select [class.red-borde ...

Searching for a file sequence using Regular Expressions in JavaScript

I have a query that needs answering: How can I utilize RegExp in JavaScript to locate strings that adhere to this filter: *[0-9].png for the purpose of filtering out sequences of files. For instance: dog001.png dog002.png dog003.png or xyz_1.png xyz_2 ...

Struggling to find a specific string in an array using the std::find() function in C++?

While working on a homework assignment, I've been tasked with finding a specific string from an array. However, I've been struggling to get the function to work for quite some time now and it's only causing me more confusion. I believe that ...

Implement a click event to trigger a search functionality within Bootstrap

I have implemented the following code to add search options in the navigation bar. It is displaying correctly, but I am not getting the click action that I require. For example, I want to trigger an action from JavaScript when the user clicks on the enter ...