Instructions for including a sentence in an array as a single element with the split method

I have a string and I want to turn it into an array by splitting it into individual elements. For example:

let str = "add 2017-04-25 2 USD Jogurt"
str.split(" ");
["add", "2017-04-25", "2", "USD", "Jogurt"]

But how can I combine two words into one element to achieve this format?

add 2017-04-25 3 EUR “French fries”
["add", "2017-04-25", "3", "EUR", "French fries"]

I have heard that regular expressions can be used for this purpose, but I am not sure how to implement it. Perhaps by splitting with another delimiter in the command: add 2017-04-25 3 EUR “French fries”

Answer №1

If you frequently encounter expression templates that follow the pattern "ACTION DATE QUANTITY CURRENCY_IN_ISO_4217_FORMAT ITEM_NAME", then utilizing regex can be quite helpful:

"purchase 2020-12-15 5 GBP Laptop".replace(/([A-Z]{3}\s)(.*)$/, '$1"Sunglasses"')

Answer №2

Why not experiment with this...

let txt = "purchase ;2021-09-10 ;5 ;USD ;Burger";
let expression = /\s*(?:;|$)\s*/;
let list = txt.split(expression);
console.log(list[4]);

Answer №3

If you prefer using a custom function instead of regex, the following code has not been tested for performance against regex.

Input string: 'add 2017-04-25 3 EUR "French crispy fries" and "tasty burger"

Output array: ["add", "2017-04-25", "3", "EUR", "French crispy fries", "and", "tasty burger"]


function myFunction() {
  var str = 'add 2017-04-25 3 EUR "French crispy fries" and "tasty burger"';
  var result = str.split(" ");
  var resultString = [];
  var quotedString = [];
  var ignoreSplit = '"';
  push = 0;
  for(var i=0;i<result.length;i++)
  {
    //start pushing if you found double quotes on starting
    if(result[i].indexOf(ignoreSplit)==0)
    {
            push = 1;
            //replace double quotes to nothing and push
            quotedString.push(result[i].replace(ignoreSplit,''));
    }
    //push if double quotes found in end
    else if(result[i].indexOf(ignoreSplit)>0)
    {
        //stop the push in between
        push = 0;
        quotedString.push(result[i].replace(ignoreSplit,''));
        //push the quoted string in main result string
        resultString.push(quotedString.join(' '));
        //empty quoted string to be used again
        quotedString = [];
    }
    //push if between the double quotes area
    else if(push == 1)
    {
        quotedString.push(result[i]);   
    }
    //push in the main result string normal case
    else
    {
        resultString.push(result[i]);
    }
  }     
   console.log('final ',resultString);
}

Answer №4

Instead of utilizing the split function, you can also opt for using match to locate either the text enclosed in double quotes or match any non-whitespace characters using an alternation.

Remember to include the global flag /g to match all instances.

/(?<=“)[^“”]*(?=”)|[^\s“”]+/g

Explanation

  • (?<=“) Positive lookbehind to confirm the presence of
  • [^“”]* Matches zero or more characters that are not or
  • (?=”) Positive lookahead to confirm the existence of
  • | Or
  • [^\s“”]+ Matches one or more characters that are not , , or whitespace

Check out the Regex demo

[
  "add 2017-04-25 2 USD Yogurt",
  "add 2017-04-25 3 EUR “French fries”"
].forEach(s => console.log(s.match(/(?<=“)[^“”]*(?=”)|[^\s“”]+/g)));

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 retrieve a collection of files with a particular file extension by utilizing node.js?

The fs package in Node.js provides a variety of methods for listing directories: fs.readdir(path, [callback]) - This asynchronous method reads the contents of a directory. The callback function receives two arguments (err, files), with files being an arra ...

The coverflow of Swiper is not displaying properly within a Div container

Just to clarify, I am not very experienced and do not know many best practices. I am learning as I go along with projects. I am using Swiper for a game list slider, but when I place it inside another Div, it disappears completely. I can position and size ...

What could be causing the constant undefined response when using ajax to post to php?

I have been using a mouseover event on a span element to trigger an ajax post call to a php page. However, I keep getting undefined values - first for responseText when using a simple echo to get the response, and now with responseXML. Can someone please h ...

Customizing the placeholder font size in Material UI Autocomplete using ReactJS

Is there a way to change the placeholder font size for Material UI Autocomplete? https://i.stack.imgur.com/x71k2.png <Autocomplete multiple id="tags-outlined" options={top100F ...

Using JavaScript to Capture a Webpage Element as an Image

Although this question has been asked in the past, I am hoping for updated information since all the answers are from a few years ago. While searching, I came across https://github.com/apollolm/phantasm, which seems to be exactly what I need. However, it ...

Removing an element from a JavaScript array that contains elements from MongoDB

Here is the array I am working with: [ { "key_id": "#K000030", "_id": "K000030", "isMaster": true, "specialties": [ { "speciality1_count": "x039", "speciality1": "Infectious Disease" } ] }, { ...

Having trouble assigning a default value to an array in the useState declaration

When attempting to set a default value for my state, I encountered an issue where it was returning undefined. However, upon refreshing the page, the values were correctly assigned to categoryIds. const si = [...searchParams.getAll("cat")]; c ...

Make sure to tick off the checkboxes when another checkbox is marked

When a specific condition is met, I want my checkboxes to automatically be checked through Javascript code in MVC. @if (str_item != "" && str_checkroles != "" && str_item == str_checkroles) { <script> src = "https://ajax.googl ...

Unique creation: Bespoke Bootstrap-Vue selection box module

Struggling to create dynamic form components, particularly with checkboxes <template v-if="type === 'switch'"> <b-form-checkbox switch size="lg" :name=" ...

How to add suspense and implement lazy loading for a modal using Material-UI

Currently, I am implementing <Suspense /> and lazy() to enhance the performance of my project. While everything seems to be working smoothly, I have observed some minor changes in DOM handling that are causing me slight confusion. Consider this scen ...

After the rendering process, the React Component member goes back to a state of

One issue I encountered is related to a component that utilizes a separate client for making HTTP requests. Specifically, when trying to use the client within a click event handler, the call to this.client.getChannel() fails due to this.client being undefi ...

The Bootstrap modal form fails to properly handle the POST method when sending data to the server

I am encountering an issue with a button that triggers a modal form <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#agregarProducto">Add Material</a> The modal appears as shown below: https://i.stack.imgur.com/J39x9.pn ...

Ways to activate the onclick function of a div element with JavaScript

I am trying to trigger the onclick event of my div using a click event in javascript. However, I am only able to trigger the onclick event using jquery. Here is the code snippet: html += '<div id="add_redirect" class="row pl_filter_v ...

Omit a certain td element from the querySelectorAll results

Greetings! I am currently working with an HTML table and I need to figure out how to exclude a specific td element from it, but I'm not sure how to go about it. Here's the HTML code: <table id="datatable-responsive" c ...

Unable to showcase the worth

My code in the render method is aimed at accessing the value of arr[1].Title, however, it seems to be causing an error. public render(){ var arr; return ( { Array.apply(null, {length:this.state.length}).map((value, i) => {i*=6; return ...

Getting the present location on Google Maps for the web: A step-by-step guide

As a newcomer to this API, I have successfully generated an API key but am unsure of how to implement Google Maps. Despite my extensive research, I have been unable to find a solution that works for me. I am seeking assistance in locating users or devices ...

Is there a way to automatically populate my form with data depending on the value selected in a dropdown menu?

I'm facing an issue with prefilling a form based on the selected value from a dropdown menu that loads invoice IDs from my database. The problem arises when trying to populate the form fields using the data corresponding to the selected invoice ID. Th ...

Challenge with URL paths in ReactJS

My webserver is up and running with all the http endpoints linked to the base URL: http://<some_name>/widget/ On the frontend, I have a ReactJS app. The issue arises after building the ReactJS app, as the built index.html references the following U ...

How can I toggle the visibility of a div based on whether a variable is defined or not?

How can I display a specific div on my webpage only when certain variables in PHP pull out a specific result from a database? I attempted to use the code snippet below, but it's not working as expected. Can someone provide guidance on how to achieve ...

Utilizing form data to dynamically create HTML content

Seeking a solution to extract data from a form similar to this one: <form id="rendered-form" name="rendered-form"> <div class="rendered-form"> <div class="fb-text form-group field-text-1534368808722"> <label class="fb-text ...