How to add character before each word in a string



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

Answer ( 1 )


    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