3

I've found that you can't use either the "forEach" or "map" functions on strings, so how would I go about going through every character in a string within JSX? Thanks for any responses.

I want to put a space between every character in a word e.g. "dog" -> "d o g".

Maltager
  • 31
  • 1
  • 3
  • @TKoL I'm sure there's a duplicate but that one is pretty old and doesn't cover the functional iteration builtins very well – Pointy Feb 19 '19 at 16:07
  • 1
    This question should not be tagged “react” or “jsx”. All processing is JavaScript related. The fact that the output can become part of the render process of a React app is totally tangential. – Pier Paolo Ramon Feb 19 '19 at 16:07
  • @Pointy - Can always add an answer that does. :-) – T.J. Crowder Feb 19 '19 at 16:07
  • Yes that's true, but on those hoary old questions new answers generally languish at the bottom of the page and nobody (especially new users) will see them. – Pointy Feb 19 '19 at 16:11

2 Answers2

5

You can call .split("") to turn the string into an array of characters, and then use .forEach() or .map() or whatever.

var s = "Hello world";
s.split("").forEach(character => console.log(character);)
Pointy
  • 405,095
  • 59
  • 585
  • 614
3

I want to put a space between every character in a word e.g. "dog" -> "d o g".

That can be done with:

const input = "dog";
const output = input.split('').join(' ');
console.log(output);

Split turns the string into an array, breaking it every time it sees a certain character. Since we're splitting on an empty string, we get an array of each character on its own.

Join takes an array and turns it into a string, putting the specified character in between each element of the former array.

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98