How to split sentence into letters

Viewed 135

I want to split text which was provided by user into single characters and then edit them.
I used RegEx to divide whole sentence into words and then into characters, but finally I got array of arrays :/

Code (check console):

function showLetters() {
  const simpleText = 'Hello my friends';
  let words = simpleText.split(/\W+/),
      letters = words.map(word => {
        return word.match(/\S/g).join();
      });

  console.log(letters);
}

showLetters();

I want to know how can I get to this letters in finall array.
I beg for help, i'm newbie

5 Answers

RegEx isn't needed here I don't think, if I understand you correctly this is what you need:

function showLetters() {
  const simpleText = "Hello my friends";
  let letters = simpleText.split("").filter(letter => letter !== " ");

  console.log(letters);
}

showLetters();

If you want the 'Blank Spaces' to remain as entities within the array, just remove the .filter part.

Just split on an optional white space, which will return all letters except white space.

function showLetters() {
  const simpleText = 'Hello my friends';
  let letters = simpleText.split(/\s?/);
  console.log(letters);
}

showLetters();

Might it not be simpler to regex replace all nonword chars with nothing, then split on nothing (Or use Array.from(string))?

str.replace(/\W/gi, "").split("");

Try this:

function showLetters() {
  const simpleText = 'Hello my friends';
  let words = simpleText.split("");

  console.log(words);
}

showLetters();

You'll get every character including white space in words array, so when you join them using .join("") you'll get words separated by white space.

Try This

<html>
    <body>
    
    <button onclick="showLetters()">Try it</button>

    <p id="demo"></p>

        <script>

            function showLetters() {

            var simpleText = "Hello my friends";
            var letters  = simpleText.split("");

            document.getElementById("demo").innerHTML = letters;
            
            }

        </script>

</body>

</html>

Related