In JavaScript replace function is basically used to replace some string in an another string. For instance, if your main string is
var main_str =”i am working as a php developer,php is favorite language “;
and you want to programmatically replace php to JAVA, you have to write the code as:
main_str = main_str.replace(/php/i,’JAVA’);
Here,as you can see we calling the replace function with the regular expression /php/i – as the first parameter which mean that it will replace only first occurrence of the string “php” but not the later ones. If we want to replace all php to JAVA we have to change the expression to /php/g – this will replace all occurrence of php in the main string.
NOTE : In replace function we have to pass a regular expression to replace. What if we want to replace a variable.
|
In replace function you can see that we are passing the regular expression to replace, but if the data is dynamic and i want to replace it in runtime ?? i have to store the data in a variable and now comes the question how i can use a variable in replace function ????
suppose you are getting the value from the textbox called subject
var subject = document.getElementById(‘subject’).value;
var main_str = “i am working as a php developer, php is favorite language “;
//i want to replace the subject variable – but as a rule in replace function we have to pass a regular exprssion
// so we cannot write main_str = main_str.replace(subject ,’JAVA’); we have to convert the subject to a regular expression
var sRegExInput = new RegExp(subject, “g”);
main_str = main_str.replace(sRegExInput ,’JAVA’);
The over all concept is that in replace function of JavaScript we can not pass a variable to replace, we have to pass a regular expression – if we want to use a variable to replace we have to convert it to regularexpression.
|