Exploring the contents of a text file using JavaScript

Trying to wrap my head around this.
It seems like the usernames are working fine, but not the passwords.
I'm extracting data from a text file with the structure "username,password".

John,BOL12345
Mary2,BOL77777
Anna,BOL54321
test,BOL12345

The first 3 entries work perfectly on their own
But if I add the entry "test,BOL12345", suddenly the password BOL12345 works
Without that additional entry, none of the passwords seem to work.
This is all happening in JavaScript, let me show you some code below.

    lines = x.responseText.split("\n");
    for (i=0; i < lines.length; i++)
    {
        test1 = lines[i].split(",")
        username.push(test1[0]);
        password.push(test1[1]);

    }
    var tempUsername = document.getElementById('username').value;
    var tempPassword = document.getElementById('password').value;
    var arraycontainsusername = (username.indexOf(tempUsername) > -1);
    var arraycontainspassword = (password.indexOf(tempPassword) > -1);
    alert(password);
    if (arraycontainsusername && arraycontainspassword) {
        window.location.href = "listing.htm";
    };

Answer №1

Based on my analysis, it appears that your file is utilizing the \r\n sequence. When you split by \n, the \r remains and corrupts each string. I suggest trying to split by \r\n instead to see if it resolves the issue. This would clarify why appending the last line may work, as there isn't a newline at the end to interfere with the indexOf search.

Different operating systems interpret text files differently. Windows employs CRLF (Carriage Return Line Feed) to transition to the next line, while *NIX variants use LF. Older versions of MacOS utilize CR. Your code assumed the file originated from a *NIX environment where LF (or \n) is prevalent, but it actually came from a Windows environment where CRLF (or \r\n) is standard (although this assumption isn't entirely accurate since you can create text files with LF in Windows and with CRLF in *NIX - but you get the idea).

To ensure proper handling under all circumstances, I recommend normalizing the string before manipulation:

x.responseText.replace(/\r\n|\r(?!\n)/g, '\n').split('\n');

The seemingly cryptic Chinese characters within the regex pattern are actually designed to match either \r\n or \r (excluding instances where \r is followed by \n). By doing so, you can convert all occurrences of CRLFs and CRs into LFs, making it feasible to process text originating from any environment.

You could simplify the regex because of token order to /\r\n|\r/, but I've retained the original version to highlight an interesting concept (lookaheads - specifically (?!\n) which denotes exclusion of immediate \n). Nonetheless, /\r\n|\r/ should yield better performance, especially when handling sizable files.

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

Is there a way to extract an array from a property value within an object using JavaScript?

Here's the code snippet under consideration: var structures = { loginStructure : function(){ return structure = [ '<form name="',opts.formClass,'" class="',opts.formClass,'" method="post" action=" ...

Items added to localStorage will not be able to store objects that have keys with array values

There seems to be an issue with how localStorage.setItem stores object values when the object contains keys with array values. var obj = data : { cachedat : ['1' , 2 , 3] }; localStorage.setItem('data' , JSON.stringify(obj) ); However, ...

Modify Knockout applyBindings to interpret select choices as numeric values

Utilizing Knockout alongside html select / option (check out Fiddle): <select data-bind="value: Width"> <option>10</option> <option>100</option> </select> Upon invoking applyBindings, the options are interprete ...

Attempting to transform a numerical value into CSS syntax

Currently, I am attempting to loop through several DIV elements, extract a numerical value from each DIV, and then based on that value matching a specific value in the JavaScript code, assign a particular CSS Class back to the original DIV. This is the sn ...

Manipulate the display of multiple elements in jQuery by utilizing data attributes

Hello there, I am currently using jQuery to filter a list of elements on a webpage based on a HTML select containing client IDs. The HTML elements have a data attribute called data-client. Unfortunately, the code I have written is causing all elements to b ...

Tips for postponing submission of a form in Prestashop

In the process of creating a carrier module for Prestashop, I have integrated two radio buttons (now,schedule). When the user selects now, the current datetime is obtained. However, if the user chooses schedule, a calendar prompt appears to select a dateti ...

Steps to combine multiple arrays into a unified array:1. Begin by allocating a

To form a league table, I have multiple individual arrays filled with data. In order to sort them by points, I want to merge these arrays into a single array called "teams". However, I am unsure if there is a function available to achieve this specific f ...

Using JavaScript requests to save XML data and PHP to read and process the XML data stored in MySQL

I have encountered an issue while trying to save XML content, received as plain text, into my site's database. I came across advice suggesting not to store XML in a text field but instead use a blob. So, I proceeded to save it as a blob using CORS and ...

Utilizing JavaScript to retrieve a property from within a method

How can I access a property from inside an object? Manually entering its path allows me to retrieve the property, but not when attempting to do it dynamically. What am I missing in the code snippet below? var myApp = { cache : {}, init: function( ...

Having trouble with the checkbox functionality. Attempting to dynamically toggle gridlines in a flot chart

First, I'll share the code and then provide an explanation. Below is a snippet of the relevant HTML: <div id='gridButton'> <form> <input type="checkbox" id="gridCheck" value="showGrid">Show Grid </form ...

Update the useState function individually for every object within an array

After clicking the MultipleComponent button, all logs in the function return null. However, when clicked a second time, it returns the previous values. Is there a way to retrieve the current status in each log within the map function? Concerning the useEf ...

Can you explain how the Facebook Like button code functions and how I can create a similar feature on my own platform?

I have a website with 250 different items, each containing its own Like button using the standard Facebook "Like" code: div class="fb-like" data-href="http://www.mywebpage.com/myproductpage" data-send="false" data-layout="button_count" data-width="80" dat ...

Traverse through nested objects

I am currently working with JSON data containing information like uf, ivp, and others. My goal is to iterate over all the objects in order to access their properties. { "version": "1.5.0", "autor": "mindicador.cl", "fecha": "2018-10-31T13:00:00.000Z", "uf ...

Struggling to implement dynamic background color changes with react hooks and setTimeout

I am struggling to update the colors of 3 HTML divs dynamically, but unfortunately the code below doesn't seem to be effective. function App() { const [redBgColor, setRedBgColor] = useState(null) const [yellowBgColor, setYellowBgColor] = useState( ...

Exploring the inner workings of view encapsulation in Angular

It is common knowledge that the default view encapsulation for a component in an Angular application is Emulated. encapsulation: ViewEncapsulation.Emulated I am quite perplexed about how it functions without being a shadow DOM. ...

Bootstrap auto-suggest feature that preloads data source on initial page load

I am attempting to dynamically load the entire source data using jQuery from the server only once on pageload. I want to store this data in a variable. The jQuery part is functioning properly, but the input is not autocompleting as expected. It only works ...

Can components in Vue.js share functions?

Within my application, there exists a plethora of utility functions that handle various tasks such as parsing strings and displaying toasts. My main inquiry is regarding how to access these functions within other .vue files without the need for redundant ...

Retrieving FormData() parameters sent via Ajax with PHP

After successfully testing FormData() with jQuery.ajax, I encountered a roadblock when trying to implement a progress bar for file uploads using the same method. This led me to use AJAX directly and post form data, but unfortunately, retrieving the form da ...

What is the best way to input text into a div that is designated as a textbox?

I am currently trying to insert text into a textbox div. Below is the HTML snippet of the element before the text was entered: <div class="_5yk2" tabindex="-1"> <div class="_5rp7"> <div class="_1p1t"> <div class="_1 ...

A fresh checkbox was added to the page using Jquery Switchery to disable it

I'm having trouble disabling the Switchery checkbox. When I try to disable it, another Switchery checkbox appears on the page along with the one I previously defined: <div class="form-group"> <label class="col-md-2"> ...