In this article we are going to explain few important use cases of String replace and how to achieve it in a faster way.
jQuery or JS string replacement functionality which returns a new string after replacing each target element with the set of matched elements. This method can be used to replace the occurrence of any string in a sentence or a group of strings.
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are to be replaced.
String replace in JS
<p id="demoPara"> ProcodersOnline.com is a platform to get quality tricks</p> <script> document.getElementById("demoPara").innerHTML = str.replace("tricks", "tricks and hacks"); </script>
String replace using CLASS or ID in jQuery
$(document).ready(function() { $("DIV with class or ID selector").html( "New Text" ); });
Jquery method is very easy to use, Because you can add nested DIV’s as well by multiple DIV’s by separating with the comma.
Globally string replace in JS
<p id="demoParagraph">Red car, Red Bike, Red taxi</p> <script> let divString = document.getElementById("demoParagraph").innerHTML; let res = divString.replace(/Red/g, "White"); document.getElementById("demoParagraph").innerHTML = res; </script>
This is used when you have to replace the Global changes. In the above code “/g” defines Global.
If you any questions please write in the below comment box.
Happy Coding 🙂
Add Comment