Last Updated : Jan 1, 2023
We have to pass two parameters first one is character needs to change and second one is to be replacing string then it will get replaced successfully and result appends on html element for display on webpage.
Here we defined div tag with id ‘res’ for appends result in webpage.
In script we defined two string variables ‘str1,str2’ with two different strings then we using replace method we replacing in str1 character ‘e’ is replaced globally with str2 ‘y’ character and replaced string stored to variable ‘re’ finally result appended to div element on html block with id ‘res’ for displayed on webpage.
<!DOCTYPE html> <html> <head> <title>STRING REPLACE</title> </head> <body> <h3>STRING REPLACE</h3> <div id="res"></div> <script> let str1="Hi Everyone"; let str2="y"; let re=str1.replace(/e/gi,str2); document.getElementById('res').innerHTML="String 1: "+str1+"<br> String 2: "+str2+" <br>Replaced String: "+re; </script> </body> </html>
- <!DOCTYPE html> tag which is instruct the web browser about what version of HTML file written in and it’s not have any ending tag.
- The<html> tag is used to indicate the beginning of HTML document.
- As above shown <head> tag is contains information about webpage and external file links are declared here. <title> tag is used for set the webpage title.
- Both <head> and <title> tags having their pair end tag, so we need to close the ending tags respectively. If you’re not closed anyone of ending tag properly that is also affect the webpage result.
- <body> tag is beginning of main coding part because it contain coding of entire website blocks and elements described here.
- In html we created <div> tag with ID ‘res’ for appends the result on webpage.
- In <script> we defined two string variables namely ‘str1,str2’ with values ‘Hi Everyone, y’ using ‘let’ keyword.
- Using replace method we replacing in string ‘Hi Everyone’ character ‘e’ replaced with character ‘y’, here ‘gi-refers replacing ‘e’ character at each place in string’ then replaced string value stored on variable ‘re’.
- Then the result is appends on html div element by ‘innerHTML’. So we appended result with div tag will displayed on webpage.
- Both </body>, </html> tags closed respectively. </body> tag indicates the end of body, Then </html> tag indicates the end of HTML document.
When we executing this program on browser we can see the result of variables str1,str2 values with replaced result string displayed on webpage.
Instead of replacing all possible particular character we can also do replace on first occurrence only by using this same concept the change is we need to give ‘g’ only instead of ‘gi’ at replace method.