Add a series of digits following every word within a given phrase

I am working on a function that is meant to add a series of numbers (starting from 1) at the end of each word within a string. Take a look at my current implementation:

function insertNum(str) {
    var src = new Array();
    src = str.split(" ");
    return src[0] + "1 " + src[1] + "2 " + src[2] + "3 " + src[3];
}

insertNum("word word word word."); // should output "word1 word2 word3 word4."
insertNum("word word word."); // should output "word1 word2 word3."

Answer №1

Here is a solution...

function addNumbers(str) {
    let count = 1;
    return str.replace(/\w\b/g, function(match) {
        return match + count++;
    });
}

View on jsFiddle.

Answer №2

A simple method:

function addNumbersToString(input) {
    let words = input.split(" ");
    let newString = "";
    for (let index = 0; index < words.length; index++) {
        newString += words[index] + (index + 1) + " ";
    }
    return newString.trim();
}

Answer №3

    int num = 1;
    String text = "What a lovely day";

    String words[] = text.split(" ");

    for(String word : words){
        System.out.print(word + num++ + " ");
    }

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

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

Struggling to manage errors within React ApolloClient

As I delve into comparing a real-world application using this Authentication server example where data is fetched, I am facing difficulties in capturing client errors. This is because Apollo Client sends its own exceptions to the console. My sample server ...

I'm experiencing an issue where my JavaScript function is only being triggered

I have a simple wizard sequence that I designed. Upon selecting an option from a dropdown menu on the first page, a new page is loaded using jQuery ajax. However, when clicking back to return to the original page, my modelSelect() function, responsible for ...

Challenges with UV wrapping in THREE.js ShaderMaterial when using SphereBufferGeometry

Currently, I am attempting to envelop a SphereBufferGeometry with a ShaderMaterial that incorporates noise to mimic the surface of Jupiter. However, the wrapping on the sphere geometry is turning out peculiarly. Instead of wrapping around the 'planet& ...

What could be causing the z-index property in CSS to fail, despite the fact that one component has a higher z-index value than the other target

Even though the z-index value of the product component is higher than that of the home-image, the home-image still dominates and overshadows the product component. In this specific scenario, the product has a z-index of 1 while the home-image has a z-index ...

Customizing Material-ui picker: concealing text field and triggering modal with a button click

I'm currently working with version 3.2.6 of the material-ui pickers library to develop a component that has different renderings for mobile and desktop devices. For desktop, I have set up a standard inline datepicker with a text input field, while fo ...

Increase the thickness of the scrollbar track over the scrollbar thumb

I've come across several discussions on making the track thinner than the scrollbar thumb, but I'm looking to do the opposite. Is it possible to have a scrollbar track that is thicker than the scrollbar thumb? ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Customize CSS to target the first and last elements in a row using flexbox styling

I am facing a challenge in selecting the last element of the first row and the first element of the last row within a flex container. The setup involves a flex-wrap: wrap; for my flex container where all elements have flex: auto; with different sizes. Thi ...

Passing information from the created hook to the mounted hook in VueJS

How can I transfer data from the created function to the mounted function in VueJS? In my VueJS application, the code in my created function is as follows: created: function(){ $.getJSON({ url: 'static/timeline.json', success:function( ...

Guidelines for breaking down a produced string within the console.log statement in JavaScript

Seeking clarification on this inquiry. I am a complete novice when it comes to coding. Currently, I have implemented the following do while loop code taken from w3s: var text = ""; var i = 1; do { text += "The number is " + i; i++; ...

Guide on dynamically importing a module in Next.js from the current file

I am facing a challenge where I have multiple modules of styled components in a file that I need to import dynamically into another file. I recently discovered the method for importing a module, which requires the following code: const Heading = dynamic( ...

Choose and duplicate all components contained within Code tag utilizing Jquery

I am in search of a jquery method to copy an entire code block. I currently have a script that copies text using the select() method, which is limited to input fields and textareas according to the jquery documentation. Therefore, I am looking for a solut ...

Enhance user experience by implementing an interactive feature that displays

I have a form for adding recipes, where there is an ingredients button. Each recipe can have multiple ingredients. When the button is clicked, an input field for adding ingredients should appear below the ingredient button. What I've attempted so far ...

What is the best way to create a mapping function in JavaScript/TypeScript that accepts multiple dynamic variables as parameters?

Explaining my current situation might be a bit challenging. Essentially, I'm utilizing AWS Dynamodb to execute queries and aiming to present them in a chart using NGX-Charts in Angular4. The data that needs to appear in the chart should follow this fo ...

jquery to create a fading effect for individual list items

I have a group of items listed, and I would like them to smoothly fade out while the next one fades in seamlessly. Below is the code I've been working on: document.ready(function(){ var list_slideshow = $("#site_slideshow_inner_text"); ...

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...

Saving, displaying, and removing a JSON document

As someone new to the world of JavaScript, I am encountering an issue with JavaScript and AJAX. I am aiming to create a function that allows me to add new elements with unique indexes. After saving this information to a JSON file, I want to display it on a ...

Is it possible to determine if a style property has been altered

I am looking to identify changes in CSS properties without needing the actual values. I only require the specific style property that has been altered. For example, I need the style property to be stored in a variable, as shown below: document.getElementB ...

The performance implications of implicit returns in Coffeescript and their effects on side effects

Currently, I am developing a node.js web service using Express.js and Mongoose. Recently, I decided to experiment with CoffeeScript to see if it offers any advantages. However, I have come across something that has left me a bit unsettled and I would appre ...