How to use a variable in replace function of JavaScript
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. Hope this tip would be useful.please feel free for any suggestions. Back to top |
|||||
All times are GMT - 8 Hours
|