www.webdeveloper.com
Results 1 to 11 of 11

Thread: can i use variable inside str.replace() ?

  1. #1
    Join Date
    Nov 2013
    Posts
    44

    can i use variable inside str.replace() ?

    i am trying a dynamic max power and "x" value input.everything is fine the problem is i can not replace the (x^something) dynamically with replace() method.
    HTML Code:
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <style>
    #gap{
        width:200px;
        height:50px;
        border:1px solid black;
    }
    thiss{
        width:200px;
        height:50px;
    }
    </style>
    </head>
    
    <body>
    <div id="gap"></div>
    <p id="thiss"></p>
    <input type="button" value="replace this" onClick="change();">
    <script>
    function change(){
        var m=document.getElementById("gap");
        var n=document.getElementById("thiss");
        var t=document.getElementById("thiss").innerHTML;
        var power=prompt("input highest power of x:");
        var i;
        var arr=new Array();
        for( i=power;i>=0;i--){
            arr[i]=prompt("coeff of x^"+i);
        }
        i=power;
        for(i=power;i>=0;i--){
            if(arr[i]>0 && i==power){
                n.innerHTML += arr[i]+"*x^"+i;
            }
            else if(arr[i]<0 && i==power){
                n.innerHTML += arr[i]+"*x^"+i;
            }
            else if(arr[i]>0 && i!=power){
        n.innerHTML += "+"+arr[i]+"*x^"+i;
            }
            else if(arr[i]<0){
                n.innerHTML += arr[i]+"*x^"+i;
            }else if(arr[i]==0){
                n.innerHTML += "";
            }
                
        }
        var x_val=prompt("solve with x =");
    i=power;
    for(i=power;i>=0;i--){
        m.innerHTML=eval(t.replace(/x\^i/,"Math.pow(x_val,i)"));
    }
        
    }
    
    
    </script>
    
    </body>
    </html>
    
    mainly problem is here.i know this is garbage .but how can it be fixed.how can i replace using variable
    HTML Code:
    for(i=power;i>=0;i--){
    	m.innerHTML=eval(t.replace(/x\^i/,"Math.pow(x_val,i)"));
    }

  2. #2
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    I didn't use your loop variable, but rather just extract the powered number from the equation instead:
    (changes are in red)

    Code:
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <style>
    #gap{
        width:200px;
        height:50px;
        border:1px solid black;
    }
    thiss{
        width:200px;
        height:50px;
    }
    </style>
    </head>
    
    <body>
    <div id="gap"></div>
    <p id="thiss"></p>
    <input type="button" value="replace this" onClick="change();">
    <script>
    function change(){
        var m=document.getElementById("gap");
        var n=document.getElementById("thiss");
        var t=document.getElementById("thiss");
        var power=prompt("input highest power of x:");
        var i;
        var arr=new Array();
        for( i=power;i>=0;i--){
            arr[i]=prompt("coeff of x^"+i);
        }
        i=power;
        for(i=power;i>=0;i--){
            if(arr[i]>0 && i==power){
                n.innerHTML += arr[i]+"*x^"+i;
            }
            else if(arr[i]<0 && i==power){
                n.innerHTML += arr[i]+"*x^"+i;
            }
            else if(arr[i]>0 && i!=power){
        n.innerHTML += "+"+arr[i]+"*x^"+i;
            }
            else if(arr[i]<0){
                n.innerHTML += arr[i]+"*x^"+i;
            }else if(arr[i]==0){
                n.innerHTML += "";
            }
    
        }
        var x_val=prompt("solve with x =");
    i=power;
    
    	m.innerHTML=eval(
    		t.innerHTML.replace(/x\^(\d+)/g, function(a, b)
    		{
    			return Math.pow(x_val, b);
    		})
    	);
    
    }
    
    
    </script>
    
    </body>
    </html>
    Code was tested, but not validated.
    JavaScript: Learn | Validate | Compact

  3. #3
    Join Date
    Nov 2013
    Posts
    44
    many thanks.but is that () outside \d+ is necessary?and the argument a and b.i am not passing any value to the arguments here.so how i can get a value Math.pow(x_val,b);
    Last edited by alzami; 12-21-2013 at 03:44 PM.

  4. #4
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    Hi,

    Yes the () is necessary in this case. It means the regular expression should capture the matching section, variable "b" in the function. Variable "a" will contain the entire match that it needed in order to pass the expression, in this case the entire match is not useful so only "b" will be used.

    Code:
    t.innerHTML.replace(/x\^(\d+)/g, function(a, b)
    {
    	return Math.pow(x_val, b);
    })
    Regular expression syntax: http://msdn.microsoft.com/en-us/libr...=vs.90%29.aspx
    JavaScript: Learn | Validate | Compact

  5. #5
    Join Date
    Nov 2013
    Posts
    44
    thanks.but how b is assigned any value ?the rule behind it.it will be helpful for me if u explain it here briefly

  6. #6
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    The String objects replace method can take a function in the replacementText argument. When a match is found the replace function will call that function passing the results found by the regular expression.

    http://msdn.microsoft.com/en-us/libr...=vs.94%29.aspx
    If replaceText is a function, for each matched substring the function is called with the following m + 3 arguments where m is the number of left capturing parentheses in the rgExp. The first argument is the substring that matched. The next m arguments are all of the captures that resulted from the search. Argument m + 2 is the offset within stringObj where the match occurred, and argument m + 3 is stringObj. The result is the string value that results from replacing each matched substring with the corresponding return value of the function call.
    Whatever result is returned by the function will become the new value for the matching section of the original string.

    Because the "g" parameter was used in the regular expression, it will continue to search and invoke that function until all matches are found/replaced.
    Last edited by bionoid; 12-21-2013 at 05:20 PM.
    JavaScript: Learn | Validate | Compact

  7. #7
    Join Date
    Nov 2013
    Posts
    44
    this explanation is good but not enriched with example.absence of good example creates more confusion.can u suggest a good source where i can learn the basics of using function as replaceText?or u can explain it by yourself.i think that would be great

  8. #8
    Join Date
    Dec 2011
    Location
    Centurion, South Africa
    Posts
    792
    I provided a link above the quote that fully describes the replace function while also providing examples. Please refer to that.
    JavaScript: Learn | Validate | Compact

  9. #9
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,252
    See too this MDN page and particularly Specifying a function as a parameter or John Resig Search and don't replace...
    Last edited by 007Julien; 12-22-2013 at 02:10 PM.

  10. #10
    Join Date
    Nov 2013
    Posts
    44
    well thanks!after studying the topics i think i am beginning to understand the topics.slowly though.i have some questions:
    as b is the captures from the string so what does it means by
    Argument m + 2 is the offset within stringObj where the match occurred
    And why m is needed here.can it be said that function is called with three arguments other than saying with m+3 arguments?
    Last edited by alzami; 12-22-2013 at 03:46 PM.

  11. #11
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,252
    The m value depends of the regExp : m is the number of left capturing parentheses in the regExp !

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles