Ads Inside Post

Search in This Blog

argument replace with string in javascript function dynamic

Problem:

Some time you want to generate dynamic button or any other control which have a click event or any other event. in that event you are replacing that's function arguments with a string value and integer value. The string value which you want to replace must be covered with double quotes "...".
See the Listed below the example:

var tr='<input type="button" value="View" onclick="sh_co(snm ,sno);" />';
you want to see the above statement as below at runtime:
<input type="button" value="View" onclick="sh_co("cpu" ,1234);"/>

Here you can notice that snm replaced with "cpu" string and sno replace as a integer 1234;
when you try to replace those string double quotes value with replace function then you will get un expected result.

So how to overcome this problem?

Solution:

To solve this problem you will use code of double quotes (") in two types. I have described this in below two examples.

The code of double quotes is &quot;

Example:



Example- 1
var tr='<input type="button" value="View" onclick="sh_co(&quot;snm&quot; ,sno);" />';
tr=tr.replace(/snm/g,"cpu");
tr=tr.replace(/sno/g,1234);

Now you can get the result as below at runtime:
<input type="button" value="View" onclick="sh_co("cpu" ,1234);"/>


Example- 2
var tr='<input type="button" value="View" onclick="sh_co(snm,sno);" />';
tr=tr.replace(/snm/g,"&quot;cpu&quot;");
tr=tr.replace(/sno/g,1234);

Now you can get the result as below at runtime:
<input type="button" value="View" onclick="sh_co("cpu" ,1234);"/>