Explain startsWith() function

Sid_Takali
Kilo Patron

Hi all, 

 I have a requirement to check a string field (compare with another field which is on another form)  and if it starts with certain word then execute a else if() block.  

function onLoad() {
   //Type appropriate comment here, and begin script below
   var value= g_form.getValue('initiated_from');
    if (value=='')
    {
        g_form.setValue('u_tracking_type',1);
    }

    else if(value.startsWith("CS")) // 
        {
            g_form.setValue('u_tracking_type',2);
        }
}

5 REPLIES 5

Aman Kumar S
Kilo Patron

The startsWith() method returns true if a string starts with a specified string.

Otherwise it returns false.

The startsWith() method is case sensitive.

 

Refer to below link for more info:

https://www.w3schools.com/jsref/jsref_startswith.asp

Best Regards
Aman Kumar

Jaspal Singh
Mega Patron
Mega Patron

Hi Siddharam,

As per my understanding startsWith() does not work in client script you can use alternatives such as indexOf() or substring()

So, something as below

indexOf()

function onLoad() {
   //Type appropriate comment here, and begin script below
   var value= g_form.getValue('initiated_from');
    if (value=='')
    {
        g_form.setValue('u_tracking_type',1);
    }

    else if(value.indexOf("CS")>-1) // 
        {
            g_form.setValue('u_tracking_type',2);
        }
}

substring()

function onLoad() {
   //Type appropriate comment here, and begin script below
   var value= g_form.getValue('initiated_from');
    if (value=='')
    {
        g_form.setValue('u_tracking_type',1);
    }

    else if(value.substring(0,2)=="CS") // 
        {
            g_form.setValue('u_tracking_type',2);
        }
}

I have a same requirement i have to check the number starts with some specific number and if yes then display error message . startsWith is not working . The field is refrence type

Aman Kumar S
Kilo Patron

To what Jaspal said, I think another way is indexOf but can be alternatively be used as:

else if(value.indexOf("CS")== 0) // check if CS value string starts with CS
        {
            g_form.setValue('u_tracking_type',2);
        }

 

Feel free to mark correct, If I answered your query.

Will be helpful for future visitors looking for similar questions 🙂

 

Best Regards
Aman Kumar