Skip to main content
1-Visitor
August 23, 2018
Solved

Javascript method 'startsWith' does not work with Thingworx

  • August 23, 2018
  • 1 reply
  • 7329 views

Hello,

I tried to use a standard Javascript method 'startsWith' which is used to determine, if a certain string begins with the characters of a specified string. But I was not able to use the same in one of my scripts. What could be the probable reason for the same?

Thanks in advance

Regards

Aditya

P.S.: Reference to startsWith

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith

My Thingworx version is "ThingWorx 8.1.0-b52"

Best answer by pgrodowski

This error seems to indicate that the Rhino Javascript interpreter does not know about the startWith method / has no implementation for it, while most things in ECMAScript 5 are supported this seems to be one of the exceptions.

 

As a workaround you can define the method yourself.

 

if (typeof String.prototype.startsWith === 'undefined') 
{
String.prototype.startsWith = function(rhs)
{
return this.indexOf(rhs) === 0;
};
}

 

This also makes it reusable for cases where startsWith does exist as it first checks if the method exists in the String prototype.

 

Let me know if you have any questions.

 

Regards,

Pascal

 

1 reply

5-Regular Member
August 23, 2018

Hello,

Can you provide a small excerpt of the script that shows the variable declaration and the first use of the startsWith method?

Do you receive any return value or nothing at all?

 

It could also be that the logic never reaches the method, I would first try to add a debug method of some sort to ensure it's called if you receive no return value.

 

Regards,

Pascal

amittal-31-VisitorAuthor
1-Visitor
August 23, 2018

Hello Pascal,

I have written a very small Service, and I run that service using the "Test" button to test it. Here is my service code

var temp = "HelloWorld";
var result = temp.startsWith("Hello");

The output of this service is set as "Boolean"

The error that I am getting is - 

"TypeError: Cannot find function startsWith in object HelloWorld."

 

Regards

Aditya

5-Regular Member
August 23, 2018

This error seems to indicate that the Rhino Javascript interpreter does not know about the startWith method / has no implementation for it, while most things in ECMAScript 5 are supported this seems to be one of the exceptions.

 

As a workaround you can define the method yourself.

 

if (typeof String.prototype.startsWith === 'undefined') 
{
String.prototype.startsWith = function(rhs)
{
return this.indexOf(rhs) === 0;
};
}

 

This also makes it reusable for cases where startsWith does exist as it first checks if the method exists in the String prototype.

 

Let me know if you have any questions.

 

Regards,

Pascal