How to add character before each word in a string

Asked by: jenniryan
Date:
Viewed: 229
Answers: 1
  • 0

Hi,

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

Answers

Answer by: ChristianKovats

Answered on: 21 Jul 2023

  • 0

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"

 

Please log in to post an answer!