How to replace a word in <p> | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to replace a word in <p>

HTML: <p id="text">Hello world!</p> How can I replace "world" to "user"?

28th Oct 2021, 6:24 AM
Fꫀⲅძ᥆͟ᥙ᥉᯽
Fꫀⲅძ᥆͟ᥙ᥉᯽ - avatar
3 Answers
+ 6
First you have to select the p element. You can use innerHTML property for changing the whole text. But as you asked how to change world to user, you can split the the whole text, store it in an array, then can change the the world to user using if statement. Alternatively you can wrap the world text in another element like span, then select the same and change it with innerHTML.
28th Oct 2021, 7:36 AM
Kashyap Kumar
Kashyap Kumar - avatar
+ 6
You can also retrieve the <p> textContent or innerHTML (it's a string) then use .replace() method to replace the first 'world' substring only, or .replaceAll() to replace all 'world' substring.
28th Oct 2021, 8:26 AM
Ipang
0
InnerHtml is a dom property can change this very easily using events
29th Oct 2021, 5:33 AM
sree harsha
sree harsha - avatar