How to add character before each word in a string

Question

Hi,

How can I add a character before each word in a string using Javascript?

Answer ( 1 )

    0
    2023-01-26T16:47:50+00:00

    You could write a function like this:

    function addCharacterBeforeEachWord(str, char) {
    // Split the string into an array of words
    const words = str.split(' ');
    
    // Loop through the array of words
    for (let i = 0; i < words.length; i++) {
    // Add the character before each word
    words[i] = char + words[i];
    }
    
    // Join the array of words back into a single string
    return words.join(' ');
    }

    Then just call the function:

    const modifiedString = addCharacterBeforeEachWord('Hello World', '*');
    console.log(modifiedString); // Output: "*Hello *World"

Leave an answer