Having major troubles with Javascript split() function - absolutely clueless!

variable = "item_1";
label = variable.split('_');
result1 = label[0];
result2 = label[1];
console.log(result1);
console.log(result2);

Expected Output:

item
1

Actual Output:

i
t

http://example.com

I seem to be making a mistake somewhere, but I can't figure out where.

I have attempted the following:

  • Experimenting with different quotation marks ' and "
  • Assigning values to variables before use (variable = ''; name = [];
  • Trying to split using a different character ('-')

Answer №1

To begin, you must define the array variable:

let names = [];

EXAMPLE http://jsfiddle.net/h23kt/9/

Reasoning Behind This Approach:

Upon further clarification requested through comments:

Even though names is not a reserved word, it can be a global property of window (e.g. window.names and names are interchangeable), declaring let names; creates a new variable called names within a different scope to prevent conflicts.

JavaScript Reserved Words: http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words

Answer №2

The issue at hand revolves around conflicts on a global scale. The global object contains a property named name which appears to be causing interference with your code.

To resolve this, you can rename it by visiting http://jsfiddle.net/j667q/3/

If renaming is not desirable, you have the option of using var name = ...split...

Additionally, it is essential to always declare variables using var. There is no justification for bypassing this practice. If you require a global property, utilize window.someName = something;

Answer №3

Make sure to properly scope your variables by declaring them with var

var path = "path_2";
var parts = path.split('_');
piece1 = parts[0];
piece2 = parts[1];
console.log(piece1);
console.log(piece2);

Answer №4

Remember, 'name' is a reserved global property in JavaScript. It's best to avoid using it to prevent any conflicts. Hopefully this information proves valuable!

Answer №5

To properly declare these variables, you will need to follow this format.

let fileName = "file_1";
let nameValue = fileName.split('_');

Feel free to view the updated JSFIDDLE (http://jsfiddle.net/prakashcbe/j667q/17/)

Answer №6

Give this a shot... Every other responses are spot on. I am unsure where you went wrong. Nonetheless, give this a try too

[http://jsfiddle.net/puvanarajan/Nytgh/][1]

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 with Ajax client-side framework while executing HTML code

When I run my project from Visual Studio using an aspx page that utilizes ajax modal popup extender, everything works fine with IE and Firefox as the default browsers. However, when I create an HTML file containing the code and open it by double-clicking, ...

Error message: Uncaught TypeError - Unable to retrieve data using POST method in react with node and express servers

I am currently working on creating a Login / Register form using react for the client-side and node / express / (mongo) for the backend. The backend functionality is working smoothly as expected, with successful storage of credentials in the database upon ...

Is there a way to bypass TypeScript decorators and instead use NestJS entities like typical types?

I am trying to find a way to work with TypeScript entities in NestJS without using decorators. Currently, I define my entity like this: import { PrimaryGeneratedColumn, Column, Entity } from 'typeorm'; @Entity() export class User { @PrimaryGe ...

The function res.render is not displaying the new page

I have a task that seems straightforward. On my header, I am loading a few a links. <a class="nav-link" href="menu">Menu 1</a> I am attempting to access the URL /menu from this link. In my app.js file: app.use('/', index); app.us ...

Issue with Ext JS: The property 'substring' is being attempted to be read from an undefined value

Hey there! I'm trying to incorporate a grid panel into my view using Extjs 4.1.1, but I keep encountering an error in the browser console that says "Cannot read property 'substring' of undefined". Below is the JavaScript code snippet I am us ...

Is there a way to modify or add to the response object's methods in Express and Node.js?

When using middleware in Express, the framework passes both a res and a req object. These objects enhance the built-in ones from http.ServerResponse and http.ClientRequest respectively. I am curious about the possibility of overriding or extending methods ...

Why is it that setTimeout was only executed once?

How can I ensure that the function NotifyMe() is only executed once for a timeout? $(document).ready(function(){ var mydata = []; $.ajax({ url: '3.php', async: true, dataType: 'json', success: function (json) { mydata = ...

Arranging elements in an array based on specified order string in Swift 3

Need help organizing an array var myArray = ["Dog", "B-1", "C-1", "C-2", "C-3","Home"] according to a specific character string order. For example, if myCustomString = "DC" Input Array: ["Dog","Goat","C-1","C-2","C-3","Home"] Desired Output Array: [ ...

Determine the ratio of the background image

I am facing an issue with layering background-images on my webpage. I have a background-image named 1 at the bottom of the page, and I want to display another div with a background-image named 2 over the bottom 5% of background-image 1 (not the bottom 30% ...

Trouble with json_encode when dealing with a multidimensional array

I've been struggling to retrieve results from 2 queries in JSON format. Even though var_dump($data) is showing the data, using json_encode either returns empty results or doesn't work at all. $data = array(); $array_articles = array(); $sql_arti ...

Aligning my website in HTML

Is it possible for me to create a similar effect on my site like the one seen here ()? The site has a background with content layered on top of it. When you scroll the page horizontally, the content remains centered until you reach the very left edge, at w ...

Effective state management for numerous instances in Vue 3 using Pinia and Element Plus

I've encountered an issue where default objects sharing the same state are causing binding problems, making it difficult to separate them. Each instance needs its own independent state management. Both parent and child components exchange data and int ...

JavaScript allows for inserting one HTML tag into another by using the `appendChild()` method. This method

My goal is to insert a <div id="all_content"> element into the <sector id="all_field"> element using Javascript <section id="all_field"></section> <div id="all_content"> <h1>---&nbsp;&nbsp;Meeting Room Booki ...

Seamless Mouse Tracking with jQuery

I am working on a project where I have my object tracking the mouse using the onmousemove event. However, I want to achieve smoother movement. I have been searching for resources in jQuery without much success. One approach I thought of is to utilize the ...

In order to properly execute the JavaScript code, it is essential to create a highly customized HTML layout from the ER

I am currently utilizing this resource to create a gallery of images on my Rails page. Here is the HTML code required to display the images: <a href="assets/gallery/ave.jpg" title="Ave" data-gallery> <img src="assets/gallery/ave_tb.jpg" alt="Av ...

How to Redirect a Webpage to the Same Tab in ASP.NET

I am currently using an asp.net hyperlink control to direct users to a web URL when the hyperlink is clicked. My goal is for the user to open a new tab, rather than a new window, when they click the hyperlink. If the user clicks the link again, I want th ...

Retrieving content dynamically using ajax

As I load comments via ajax, I start with 5 by default and allow the user to request more. My query is centered around the best approach. What is the optimal location to construct the HTML elements meant for display on the page? Would it be better to cr ...

Can you explain the process for moving a div to align with another div?

Having just started with HTML and jQuery, I am looking to create three draggable divs stacked one below the other - div1, div2, and so on. I want to drag div1 into the position of div3, changing the order to div3, div1, div2. How can this be achieved? Ple ...

Center Align Images in HTML List Items

Hey there! I'm currently diving into the world of web development with responsive design, but I'm still a bit of a newbie. So please bear with me as I try to explain my issue in detail. If you need more information, just let me know! My current ...

What is the proper way to address the issue of nesting ternary expressions when it comes to conditionally rendering components?

When using the code below, eslint detects errors: {authModal.mode === 'login' ? <Login /> : authModal.mode === 'register' ? <SignUp /> : <ForgotPassword />} Error: Avoid nesting ternary expressions. eslint(no-nested-t ...