Remove leading characters from string ONLY if it is followed by a hyphen

heathers_
Kilo Sage

Hello,

How would I script removing all characters from a string ONLY if it is followed by a hyphen? I do not want the characters removed if the hyphen is not at the end. 

Example: hello- (should return null)

OR

hello (should return hello since there is not a hyphen)

 

Thanks!

 

1 ACCEPTED SOLUTION

ccajohnson
Kilo Sage

For this example, our source column is called User ID, which is the equivilant of u_user_id. Feel free to change the source field to whatever the source field is for your import. Taking the function Michael used, I have created the script that you can use for the user_name target field (I am guessing that this is the target field):

answer = (function transformEntry(source) {
    var chkString = source.u_user_id.toString();
    if (chkString.endsWith('-D')){
        return '';
    } else {
        return chkString;
    }
})(source);

View solution in original post

6 REPLIES 6

Brian Lancaster
Tera Sage

I would just do an if statement like this and then overwrite my current string with an empty one.

if (filed.toString().indexOf('-') > -1){

    set value of filed to null

}

I am mapping the user_name in a transform map. If the source value has a "-D" at the end, it indicates this value has been deleted and the target reference field needs to be null. Will this help accomplish this task? Currently it is blanking the value even if it shouldn't.

Can you share you exact coding?

Michael Ritchie
ServiceNow Employee
ServiceNow Employee

The JavaScript endsWith function is better for this use case

if (source.user_name.endsWith("-D")) {
    // do something
}

 

Informationally there is also a startsWith function too.