Home > Blockchain >  Include all characters using regular expressions
Include all characters using regular expressions

Time:11-19

i'm not very familiar with regular expression, and i'm trying to solve a problem in pure Javascript.

i'm using replace() tu cut out a string into words (divs), then words into letters (span), to animate all the letters separately

But using my code below, only letters are taken into consideration.
I need to include everything (alphanumeric, special characters, ...)

<p >Hello! My name is John Do.</p>
.about-line {
 border: solid 2px blue; 
  display: inline-block;
}
.letter {
 border: solid 1px red;
}
var cutText = document.querySelector(".string");
cutText.innerHTML = cutText.textContent.replace(
  /\w /g,
  (word) =>
    '<div >'  
    word.replace(/./g, "<span class='letter'>$&</span>")  
    "</div>"
);

Any help would be appreciated.
Thanks

CodePudding user response:

You can match 1 or more non whitespace characters \S to get all the "words", and then still use the dot to get every character (as you only have non whitespace characters left in that match)

var cutText = document.querySelector(".string");
cutText.innerHTML = cutText.textContent.replace(
  /\S /g,
  (word) =>
  '<div >'  
  word.replace(/./g, "<span class='letter'>$&</span>")  
  "</div>"
);
.about-line {
  border: solid 2px blue;
  display: inline-block;
}

.letter {
  border: solid 1px red;
}
<p >Hello! My name is John Do.</p>

  • Related