How to use if (gs.getUserName().startsWith('abc')) in Knowledge Articles User Criteria.

Kunal Sharma2
Tera Contributor

The below mentioned code is not working for user criteria.

For providing read only access to users who's ID startswith either A or B.

if(gs.getUserName().startsWith('A') || gs.getUserName().startsWith('B'))
{
answer = true;
}
else
{
answer=false;
}

find_real_file.png

3 REPLIES 3

Allen Andreas
Administrator
Administrator

Hi,

It's recommended to use the pre-defined user_id variable per documentation and not use gs.getUser or other session APIs. Example here:

https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0780775

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!

Hi Allen,

How to check whether the logged in userid starts with a specific letter in the user criteria.

We are facing an issue where the user is not able to view the KB article, we are using the below script now. Changed it according to the link provided.

var userGR = new GlideRecord('sys_user');
userGR.get(user_id);
if(userGR.getValue("user_name").startsWith("z") || userGR.getValue("user_name").startsWith("q") || userGR.getValue("user_name").startsWith("y"))
{
answer = true;
}
else
{
answer = false;
}

Thanks

Hi Kunal,

I'm glad my reply above helped you. Please mark it as Helpful, if so.

When you're using "startsWith", it's going to consider case as well. Meaning, if those user_name values start with "Z" and not "z", your script won't find it. You'd want to consider that when writing your script.

With that said, you aren't supplying much other details other than your script. What is an example user_name of a user you're saying this isn't working with?

Have you tried to verify everything using the user criteria diagnostics feature? https://docs.servicenow.com/bundle/paris-servicenow-platform/page/product/knowledge-management/conce...

Please attempt that as well.

Finally, here's some possible assistance with your script that may resolve your issue:

var userGR = new GlideRecord('sys_user');
userGR.get(user_id);
var uName = userGR.getValue('user_name');

if (uName.toLowerCase().startsWith("z") || uName.toLowerCase().startsWith("q") || uName.toLowerCase().startsWith("y")) {
answer = true;
} else {
answer = false;
}

The above is an example. It's also recommended to use log statements to help you troubleshoot...otherwise you're just coding in the dark.

Please mark reply as Helpful/Correct, if applicable. Thanks!


Please consider marking my reply as Helpful and/or Accept Solution, if applicable. Thanks!