Transforming an Array into a String and Extracting a Substring

I started with a numeric array in JavaScript and converted it to a string using the join method. However, when attempting to extract a substring using substr, I encountered a technical issue. Can someone please assist me with this problem?

var array = [85, 13, 7, 42, 78, 9];
$("#div1").html("<b>This is the original array:</b><br><br>" + array.join("<br>"));

$("#div2").html("<br><b>This is the converted string:</b><br><br>" + array.join(""));

$("#div3").html("<br><b>The substring (from 0 to 3) is:</b><br><br>" + array.substr(0,3));

PLEASE NOTE: The elements with IDs div1, div2, and div3 represent separate divs where I intend to display the respective results.

Answer №1

When using substr, it's important to remember to apply it to the result of the array.join function, not directly on the array itself. This is because join does not alter the original array; instead, it returns a new string value.

To correctly use substr, first store the result of array.join("") in a variable, and then apply substr to that variable.

var joined = array.join("");
joined.substr(0,3); // this approach will yield the desired outcome

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 an attribute to the Treeselect Vue component from a Laravel view

I want to encapsulate Vue-Treeselect link: within its own custom vue component. This way, I can easily use something like <tree-select></tree-select> in a Laravel view file where needed. However, the challenge I'm facing is figuring out ...

Using Scrapy and Selenium to interact with dynamic elements on a webpage

When I crawl the page, I come across an element that looks like this. <a class="a-declarative" href="javascript:void(0)" data-action="a-expander-toggle" data-a-expander-toggle='{"allowLinkDefault":true, "expand_prompt":"See more", "collapse_pro ...

Click event on child element causing parent element to also be triggered - React.js

Here is the code snippet in question: <ul className="sb-modules-list"> <li key={index} className={this.getModuleClass(module)} onClick={() => { alert(127) }}> <ul className="sb-module-steps-list"> { module.steps ...

Optimal method for linking NodeJS and Angular in a seamless integration

I am currently working on developing a web application that integrates a Node server as the backend and Angular for the front end. At the moment, my application consists of two JavaScript files: server.js and controller.js. Below is the code snippet for ea ...

Sorting Arrays within an Array in PHP

My current array structure looks like this: array { [0] => array { [0] => array { ["Time"] => "01:00:00" } [1] => array { ["Time"] => ...

Designate the preferred location for requesting the desktop site

Is there a way to specify the location of the 'Request desktop site' option? Here is the code I am currently using: var detector = new MobileDetect(window.navigator.userAgent); if(detector.mobile() != null || detector.phone() != null || det ...

Arrange the elements of the array in MongoDB based on the last element

Seeking a way to sort documents based on the last interaction, utilizing an array called meta_data.access_times. This array updates every time a user interacts, with a new date object being added to its last element. Is there a method to sort by the last e ...

Hide the external div if the tab is active in Angular Bootstrap

How can I determine if a specific tab is active and then hide a div outside all tabs when it is active? Plunker: https://plnkr.co/edit/b9O9S7JxxgzhQKcKONkn?p=preview <div class="border"> Conceal me when Tab #3 is active. </div> < ...

Add an element to a nested array using the array_push function

Below is the code snippet I am working with: $return_array = array( $count_answers => array( "name" => $domain, "type" => $type, "class" => $class, "tt ...

Is the array empty once the functions have been executed?

app.post('/api/edit-profile', regularFunctions, async function (req, res) { let email = req.body.email let password_current = req.body.password_current connection.query('SELECT * FROM accounts WHERE id = ?', req.body.id, asy ...

What is the best way to deduct a variable's previous value from the final value, ensuring that the total value does not surpass a specific limit?

For instance: let num = 20; const sub = 6; const add = 10; num = num - sub; num = num + add; if (num > 20){ num = 20; } console.log("Only 6 was actually added to var num before reaching its maximum value"); Is there a way to adjust the console log ...

Using Vercel for a Next.js Custom Directory Configuration

Seeking guidance on deploying Next.js with Vercel, I have made changes to the structure of my Next.js project: frontend (Current Directory for Next.js) node_modules next.config.js jsconfig.json package-lock.json package.json Contents of package.json scri ...

Issue with implementing setCallBack for updating variant prices in Shopify

I'm currently attempting to update the price of a product when a variant is chosen. I've tried implementing the following code, but haven't been successful in getting it to function properly. The script has been added to the theme.liquid fi ...

How can I generate spheres in threejs with varying radii while all passing through the shared point located at coordinates (0,0,200)?

Is there a way to generate spheres in threejs where the radius increases while always passing through a single point at 0,0,200? This would allow the origin of each new sphere to move along the z-axis. Appreciate any help, AriemWebgl ...

How to Filter a Nested Array of Custom Objects using Swift

Below is the filtering mechanism I use for my Custom Object Array utilizing a SearchBar. func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText != "" { searchedData = data.filter({ ...

Is the initial carousel element failing to set height to 100% upon loading?

If you take a look here, upon loading the page you will notice a DIV at the top. It is labeled "content" with "content_container" wrapped around it and finally, "page" around that. Clicking the bottom left or right arrows reveals other DIVs with similar ta ...

Discovering the final element of ng-content while conducting tests using Protractor

I am searching for the always last element to click on. This is what I see when I inspect the page. https://i.sstatic.net/DMXQ8.png https://i.sstatic.net/ZkbER.png ...

Troubleshooting: Why are my images not displaying in webpack and node.js setup?

My problem: I'm facing an issue with background images in my project. I have included two images and used file-loader to bundle them through webpack. While the images display correctly in the app during development using webpack-dev-server, they disap ...

Unleashing the potential of an endless animation by incorporating pauses between each iteration

I am trying to create an infinite animation using animate css but I want to add a delay between each iteration. After exploring various options, I first attempted to achieve this using plain JavaScript. Here is the HTML snippet: <div id="item" class= ...

The interface 'children: string' does not share any properties with the type 'IntrinsicAttributes'.ts(2559)

When I export the component, the value from the input email does not appear as a VALUE property. How can I collect the text written in this exported component in my code? NOTE: I am working on developing a design system using STORYBOOK. export const Login ...