JavaScript's string splitting functionality is not working as expected

I'm attempting to break apart a string using the delimiter \$, but my attempts so far have been unsuccessful.

You can find the code I've been working with at . I've also included it below for reference.

Question: Can you spot what’s going wrong in this instance when splitting by \$?

var trickyString = "sd sewq wee r r ttttt $300 rrtrt utu iwiwi \$500 kjgf ihj \$215 ghi"; 

//document.getElementById("div0").innerHTML = trickyString;

function splitString() {
    //Why doesn't splitting by \$ result in 3 elements as expected, but instead gives 4 elements?
    var array1 = trickyString.split(/\$/);
    document.getElementById("div1").innerHTML = "<b>Length = " + array1.length + "</b>";
    for (var i = 0; i < array1.length; i++) {
        document.getElementById("div1").innerHTML += "<br>" + array1[i];
    }

    var array2 = trickyString.split("$");
    document.getElementById("div2").innerHTML = "<b>Length = " + array2.length + "</b>";
    for (var j = 0; j < array1.length; j++) {
        document.getElementById("div2").innerHTML += "<br>" + array2[j];
    }
}
<button onclick="splitString();return false;">Split a tricky string</button>

<h4>Tricky string</h4>
<div id="div0" style="color:green">sd sewq wee r r ttttt $300 rrtrt utu iwiwi \$500 kjgf ihj \$215 ghi</div>

<h4>Split using \$ as delimiter</h4>
<div id="div1" style="color:red"></div>

<h4>Split using $ as delimiter</h4>
<div id="div2"  style="color:blue"></div>

Answer №1

The root of your problem lies in the regex /\$/, where the \$ is being treated as a literal character.

To resolve this issue, use /\\\$/ instead. Check out an example on regex101.com

\\ matches the character \ literally (case sensitive)
\$ matches the character $ literally (case sensitive)

https://i.sstatic.net/FEDl6.png

You're encountering a similar problem in your string, using \$ makes it interpret the $ literally. To fix this, double escape the quote marks:

const trickyString = "sd sewq wee r r ttttt $300 rrtrt utu iwiwi \\$500 kjgf ihj \\$215 ghi;"

Answer №2

One issue lies in the fact that slashes hold significance both in a JS String and in a RegEx.

The following components are crucial:

var trickyString = "sd sewq wee r r ttttt $300 rrtrt utu iwiwi \$500 kjgf ihj \$215 ghi"; 

Modified to:

var trickyString = "sd sewq wee r r ttttt $300 rrtrt utu iwiwi \\$500 kjgf ihj \\$215 ghi"; 

This alteration is necessary as \$ will otherwise be read as $.

Additionally:

var array1 = trickyString.split(/\$/);

Should be amended to:

var array1 = trickyString.split(/\\\$/g);

This adjustment ensures that \$ is recognized as $; hence, the initial \\, while recognizing that $ itself has special connotations, warranting the second \$.

The given code reads as follows:

var trickyString = "sd sewq wee r r ttttt $300 rrtrt utu iwiwi \\$500 kjgf ihj \\$215 ghi"; 

//document.getElementById("div0").innerHTML = trickyString;

function splitString() {
    //Why is splitting by \$ not giving 3 elements but is instead giving 4 elements?
    var array1 = trickyString.split(/\\\$/g);
    document.getElementById("div1").innerHTML = "<b>Length = " + array1.length + "</b>";
    for (var i = 0; i < array1.length; i++) {
        document.getElementById("div1").innerHTML += "<br>" + array1[i];
    }

    var array2 = trickyString.split("$");
    document.getElementById("div2").innerHTML = "<b>Length = " + array2.length + "</b>";
    for (var j = 0; j < array1.length; j++) {
        document.getElementById("div2").innerHTML += "<br>" + array2[j];
    }
}

The outcomes of this script are depicted below:

Tricky string
sd sewq wee r r ttttt $300 rrtrt utu iwiwi \$500 kjgf ihj \$215 ghi
Split using \$ as delimiter
Length = 3
sd sewq wee r r ttttt $300 rrtrt utu iwiwi
500 kjgf ihj
215 ghi
Split using $ as delimiter
Length = 4
sd sewq wee r r ttttt
300 rrtrt utu iwiwi \
500 kjgf ihj \

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

Error encountered while trying to retrieve JSON data

After running the following code, I encountered an issue I received an error message stating: Uncaught TypeError: Cannot read property 'searchname' of undefined What could be causing this error and how can I fix it? var selectedVal = "calend ...

AngularJS: steer clear of relying on the 'angular' global variable

Is it advisable to refrain from using the 'angular' global object within Controllers, Services, etc? Suppose we want to call the function: angular.isDefined(myVar) How should we reference the 'angular' object? Possible approaches: ...

JavaScript - unique user-defined data types - what skills do I need and what knowledge should I acquire?

Exploring the vast flexibility of JavaScript, I've been intrigued by the idea of creating a custom data type that mimics the behavior of native JS types. My goal is to develop a range data type capable of representing math ranges such as (2.5;9] or (- ...

Eliminate Redundancy with Knockout.js Copy Prevention

When I combine both ko.js files, one of them ends up being overshadowed by the other. Specifically, the second one stops working while only the first one remains functional. How can I merge these files together to ensure they work properly without any conf ...

Experiencing difficulties with a cross-domain jQuery/AJAX service request

After extensively researching various threads both on this platform and elsewhere, I have been trying to successfully execute a cross-domain AJAX call. The scenario involves a Restful WCF service that simply returns a boolean value. The service is configur ...

Cookies in Chrome must be set with the assistance of a server

I recently completed a small project that does not rely on a server for functionality. In this project, I utilized cookies to store and retrieve values. Surprisingly, the project works seamlessly in Firefox, Safari, and IE 9 as it successfully sets and ret ...

Find all child elements in Jquery that meet a specific condition

Within my HTML document, I have a div element with the id='tips'. This particular div contains multiple child elements. My objective is to retrieve a specific child of the div with the id='tips' that has its style attribute set to top & ...

Issue displaying updated table data following concatenation in Ionic 3 using Angular 4

In my current implementation, I am utilizing Ionic's events to transfer data between pages. Specifically, I am attempting to pass an array containing two objects to another page. The targeted data that I want to modify is named dataOne. To achieve thi ...

Tips for extracting the index of the chosen item from a dropdown using ReactJs and Material UI

This is the code snippet for Dropdown component implementation: <DropDownField name={formElement.name} label={formElement.name} value={formik.values[formElement.name] || ''} dropDownItems={formElement.name === &apo ...

Playing around with the YUI function

I have a file named signup.js, which includes a function called demo(). This function makes a call to another YUI library function with the following arguments: Y.io('mywrongserver', callbackfunction); I need to test this function, but I want t ...

The Bitcoin API response is coming back with a null body

I have been diving into the world of APIs and am currently working on a web application that converts cryptocurrencies to fiat currencies. However, I am facing an issue while trying to parse the JSON from the API call. Every time I attempt to do so, I enco ...

Implementing a function to navigate to a different page using jQuery mobile

I'm attempting to pass a function when changing pages in jQuery Mobile, but I keep getting an error that points to `$.ajax` $( ":mobile-pagecontainer" ).pagecontainer( "change", "#schoolperformance", { reload : true, showLoadMsg : false, ...

JavaScript for Extracting Child Elements from XML

Below is the XML format I am working with: <Result> <system> <STATIC> <Tag1>2015-10-29T02:02:38-08:00</Tag1> <Tag2>264000000</Tag2> <Tag3>32696320</Tag3> </STATI ...

Performing two simultaneous AJAX requests using tokeninput

I've been playing around with the tokeninput plugin and it's been working really well for me. However, I recently came across a new requirement - I need to make two separate ajax calls on the same input bar. Situation: My input bar is as follows ...

When an icon is hovered over in Vue, a text box popup will be displayed

Working on a personal project that requires obtaining the status of all devices within a unit. The status, along with the device name, is returned in an array from the function deviceStatus(). If all devices are currently marked as ON, the home icon next t ...

Exploring AngularJS - Understanding how dependency injection works in services, factories, filters, and beyond

Currently, I am using plugins and libraries in my Angular app by directly referencing their functions/methods without considering dependency injection. This approach is common in most apps, but I want to optimize the use of these resources. One such libra ...

Display an image in a new window

Hey, I want to display an image in a separate window when it is clicked. Here is my HTML code snippet: <div data-role="content" class="jqm-content"> <h2>Photo popup example</h2> <div data-demo-html="true"> <a href="#popup ...

Using string replacement for effective search finding: Unleashing the power of substring matching

I have a method that adds an anchor tag for each instance of @something. The anchor tag links to a specific sub URL. Check out the code: private createAnchors(text: string) { return text.replace(/(@[^ @]+)/ig, '<a href="/home/user/$1">$1& ...

JavaScript basic calculator app failed to generate an error as anticipated

For my homework assignment, I am developing a basic calculator application using JavaScript. My main task is to ensure that the input numbers are limited to only two and that they are valid numbers; otherwise, an error should be thrown. Initially, concern ...

Angular app with built-in PDF viewer

Are there any reliable PDF viewer components available for viewing PDF files within my Angular application? I've attempted using angular-pdfjs-viewer, but unfortunately, it did not function as expected. Currently, all I have is a link to the PDF file ...