concatenation

MIck11
Kilo Contributor

I am trying to concatenate two string fields and nothing seems to be working. Anyone have any idea

 

 

14 REPLIES 14

@MIck 

Just replace my script in OnChange Client script..

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    var field1 = g_form.getValue('u_raghu');
    var field2 = g_form.getValue('u_last');
    var conCat = field1 + field2;
    g_form.setValue('description' , conCat);
}

I hope it definitely helps you, if so then please mark it as correct and helpful.

@MIck have you tried my suggestion?

Gaurav Shirsat
Mega Sage

Hello 

var text1 = "Service";
var text2 = "Now";
var result = text1.concat(text2);

as per,

The concat() method joins two or more strings.

The concat() method does not change the existing strings.

The concat() method returns a new string.

Syntax: string.concat(string1, string2, ..., stringX);

 

Simply we can even concatenate, in script as : using +

client script: 

 

var text1="Service";
var text2="Now";
gs.print("I am "+text1+text2+" Developer");
 
Output:- I am ServiceNow Developer
 
 
Mark my Response as Correct or Helpful, if you find it Appropriate.
Gaurav Shirsat : ServiceNow Community MVP 2022
https://www.linkedin.com/in/gauravshirsat/

 

MIck11
Kilo Contributor

Everything executes but i am getting a sysid populated if its not much trouble how do i convert the sysid to String so its readable to humans.

Hitoshi Ozawa
Giga Sage
Giga Sage

There's 3 ways to concatenate a string in JavaScript.

Method 1 which is the most common is to use the "+" operator. 

var grade = g_form.getValue('u_grade');
var step = g_form.getValue('u_step');
g_form.setValue('u_grades',grades + step);

When using the "+" operator, be sure that at least one of the operand is a String. If both are numeric, sum will be returned instead.

That is, 1+2 will return 3, while "1" + 2 will return 12.

As an aside, JavaScript allows using "+=", but this will cause an error in Service Now so it's necessary to use "=". 

e.g.

var a = "hello";
//var b += " world";   // will cause error
var b = b + " world";  // OK

 

Method 2. Use concat(). This is rarely used.

var grade = g_form.getValue('u_grade');
var step = g_form.getValue('u_step');
g_form.setValue('u_grades', grade.concat(step));

Method 3. Use join(). Join concatenate all elements in an array.

var grade = g_form.getValue('u_grade');
var step = g_form.getValue('u_step');
g_form.setValue('u_grades', [grade, step].join(''));

concat() is not used often because if the first operand is null, it would cause and error. If the argument is null, it would return a "null". "+" operator would work even if one of the operator is null.

This actually isn't a problem with .getValue() would always return a String, but it's uncommon to see concat() used in JavaScript because "+" is faster than using "concat()".