How to pass string value as reference in javascript and change it there

How to pass string value by reference in javascript.

I need such functionality.

    //Library.js
    function TryAppend(strMain,value)
    {
    strMain=strMain+value;
    return true;
    }

    //pager.aspx

    function validate()
    {
    str="Checking";
    TryAppend(str,"TextBox");
    alert(str); //expected result "Checking" TextBox
    //result being obtained "Checking"    
    }

How to do it.

+5
source share
3 answers

You cannot pass a value by reference in JS. You can create an object with a function that will do this for you:

function TryAppend(originalValue) {

    // Holds the value to return
    this.Value = originalValue;

    // The function joins the two strings
    this.Append = function (append) { 
        this.Value+=append; 
        return true;
    }

}

Then you can use this in any method as follows:

function AnyProcedure() {

    var str = "Checking";
    var append = new TryAppend(str);
    if (append.Append("TextBox")) {
        alert(append.Value);  // Will give "CheckingTextBox"
    }

}

Each time you call append, it is added to the value string. I.e.

If you have done this:

append.Append(" Foo");

append.Value will be equal to CheckingTextBox Foo.

+4
source

You need to return String instead true!!

    function TryAppend(strMain,value)  { 

    strMain=strMain+value; 

    return strMain; //you need return the  'String Value' to use in it another method

    } 


    //pager.aspx 


    function validate() { 

    str="Checking"; 

    str = TryAppend(str,"TextBox"); 

    alert(str); //expected result "Checking" TextBox 

    //result being obtained "Checking"     
    } 
+1

(, gblstrMain) TryAppend, strMain .

    var gblstrMain;

function TryAppend(strMain,value)
    {
    strMain=strMain+value;
    gblstrMain = strMain;
    return true;
    }

    //pager.aspx

    function validate()
    {
    str="Checking";
    TryAppend(str,"TextBox");
    str = gblstrMain;
    alert(str); //expected result "Checking" TextBox
    //result being obtained "Checking"    
    }

Since you are particularly confident in returning true in the TryAppend function, we can achieve this workaround.

+1
source

All Articles