I need to change the font of all digits in the page.
I thought about using insertBefore()
and so on – but then I realized it can’t be used with strings.
What I currently have:
-
An array with all the text in the page.
-
An array with all digits.
-
An array with all digits replaced with the
replace()
function (A failed attempt).
I also tried to create a for
loop that would loop over all words in the array and assign them an element created with a variable – but apparently they can’t be accessed.
How could I wrap all items of the 'string'
array with a span
or any other tag?
NOTE: I’d rather not use innerHTML
.
Thank you very much!
let allText = document.querySelector('body p').textContent;
console.log(allText);
let digits = allText.match(/d/gi);
console.log(digits);
let rep = allText.replace(/d/gi, "AA");
console.log(rep);
document.body.textContent = rep;
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {
text-align: center;
font-size: 40px;
}
</style>
</head>
<body>
<p>
sdfjsdf
(1): sdfdsdfs --
(1): sdfdsdfs --
(2) sdfsdf --
(3): sdfsdfs --
sdfdsfsdf --
</p>
<script src="a.js"></script>
</body>
</html>
2
Answers
As long as there are no numbers inside tags inside the content
I changed to
pre
to keep the listNOTE: The use of innerHTML CAN have some XSS issues. If the content of the P tag has not been sanitized, you do run a risk. So here is a version that is XSS safe. I just read in your comment that you did not want innerHTML anyway
If you are not bothered, then here is a simpler version
If the objective is to wrap each number sequence in the document, here’s one approach: