Issues with the split() function in JavaScript causing it to malfunction

I'm attempting to separate a string into different parts:

var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"

var res = device_data.split('*');

However, this code isn't functioning as expected. It just presents the original string.

  var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"

  var res = str.split('*'); 

  console.dir(res)

,HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#,HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555

Instead of achieving an array with two distinct elements.

Answer №1

In my humble opinion, the code you're looking for might resemble the following:

let message = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"

let splitMessageArr = message.split('*').filter(item => item !== "")

console.log(splitMessageArr)
console.log(splitMessageArr[0])
console.log(splitMessageArr[1])

Answer №2

When you receive a string with a period at the beginning, it's because the process you're following ends up turning the result of String#split into a string. String#split actually gives back an array. When an array is converted to a string, it takes on the form of element0,element1,element2 ... elements separated by commas.

In this particular scenario, the outcome of String#split is ["",...] with 3 elements due to the initial character being '*', which gets treated as an empty string in the resulting array. So essentially, the result aligns with expectations and String#split is functioning correctly.

If you want to remove that first character from the string,

mystring.substr(1).split('*')

To eliminate any empty strings,

mystring.split('*').filter(s=>s!='')

This will give you the desired output.

Answer №3

Here is a helpful code snippet:

  • let result = str.split("#");

You can easily test this in the browser's Javascript console.

A great tip is to utilize the browser console, such as Chrome, for running quick scripts like the one mentioned above.

This method can save you time by making it simpler to inspect your data structures and their contents.

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

Answer №4

When attempting this method,

let result = sentence.split('*');

You will end up with a total of three distinct parts:
result[0] is an empty string
result[1] is 'HQ,61...'
result[2] is 'HQ,...'

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

Sending the size of an element back to the Controller in AngularJS: A guide

In my AngularJS application, I am faced with a dilemma regarding a container div that needs to dynamically adjust its size based on the available space within it. The challenge lies in the fact that the container div is styled using percentages in CSS (e. ...

Ensuring consistency of variables across multiple tabs using Vue.js

In my vuejs front-end, a menu is displayed only if the user is logged in. When I log out, the variable isLogged is updated to false, causing the menu to hide. If I have multiple tabs open with the frontend (all already logged in) and I logout from one tab ...

Utilizing emotion with MUI v5 for dynamic theming

After upgrading MUI from v4 to v5, I'm facing some difficulties grasping the concept of theming with the various solutions available. I find it challenging to determine when to use MUI theming/styling components and when to opt for emotion ones. Whil ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

Utilize the ionicPlatform.ready() method for implementing a service factory

Within my app.js file, I have the following method: .run(function($ionicPlatform) { $ionicPlatform.ready(function() { gvi.Notifications.registerForPush(MessagesService.onNotificationResponse); }); }) Additionally, I have a factory ...

Enter data into a static grid using asp.net

Currently, I am working on developing a data entry application and I have a vision for how I want it to be designed and operate. Specifically, I envision a static grid where users can click on cells to make edits. I have included an image showcasing this l ...

Using PHP, JavaScript, and Bootstrap to display success or error messages for form fields through AJAX

I am working on a form where users input an 'authorisation code' that is then checked against a database using AJAX and PHP. Currently, the form displays a tick if the code is valid and a cross if it is incorrect. I would like to utilize Bootstra ...

Accessing variables from child controllers with populated select inputs in Angular

I'm currently facing an issue involving 3 controllers: Parent Controller: DocumentController Child Controller1: XdataController Child Controller2: CompanyController The child controllers are used to populate data in three Selector inputs on the fron ...

What is the best way to retrieve the variable value following the $getJSON method call?

Within the following code snippet, I have a function called counter that increments a global variable. This function is used to count elements within a JSON file. My query pertains to retrieving the value of the counter after the $getJSON call. I am puzzle ...

Design a circular progress bar with a cut-off at the bottom

Does anyone have suggestions on how to create a circular progress bar with cropping at the bottom, similar to this example: PROGRESS BAR? I've been searching for a component like this but haven't had any luck. Any ideas, especially utilizing Mate ...

Loop through a JSON object using a sequence of setTimeout() functions

After running another function, I have retrieved a JSON object stored in the variable 'json_result'. My objective is to log each individual JSON part (e.g. json_result[i]) after waiting for 5 seconds. Here was my initial attempt: for (let key ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

What is the process for obtaining the data value from an 'SVG path'?

Is there a way to extract the data d="M75.5 299.5 111.5 299.5 111.5 311.5 75.5 311.5 z" and use it for creating another element? <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="670px" height="400px" style="position: relative; display: bl ...

Grails is experiencing a surge of duplicate events being triggered simultaneously

In my _test.gsp layout, I have a 'click event' that is triggered when the layout is rendered as shown below. <div id="testid"> <g:render template="test"/> </div> When I click on the event in the _test.gsp layout, it trigge ...

Unable to assign values to textarea and checkbox in MVC5

I am currently facing an issue with setting values in JavaScript + jQuery in MVC 5 for textareas and checkboxes. Here is the JavaScript code I am using: document.getElementById("UpdatetxtDescription").value = "abc"; document.getElementById("Upda ...

In JavaScript, the handleSubmit function is effective, whereas in TypeScript React, it presents some

Currently, I am attempting to manage form submission in React using external functions and encountering an error message specific to Typescript React. Parameter 'event' implicitly has an 'any' type.ts(7006) Below is the code snippet ca ...

What is the best way to bring a module into an Angular project?

I have a project in Angular with an additional module created as an npm package. The structure of the module is as follows: --otherModule --other-module.module.ts --index.ts --package.json index.ts: export { OtherModule } from './other-module ...

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...

Ordering Arrays based on a particular attribute

My array includes user points as follows: let groupRank = []; userA = ["Sara", "24"]; userB = ["John", "12"]; userC = ["Eddi", "20"]; userD = ["Marry", "13"]; I am looking to rank them according to their points and achieve the following result: Console ...

I encountered an issue where I am unable to subtract from jQuery's .outerHeight() within an if statement

I've been working on creating an ajax request that triggers when a div is scrolled to the bottom. I thought I had it figured out with this code, but I've run into an issue. Everything works fine without subtracting 100 from the elem.outerHeight() ...