Whilst developing a Windows procedure using JScript, it seems that some string methods fail to work. In this example using trim, line 3 generates the runtime error:
"Object doesn't support this property or method".
My code:
strParent = " a ";
strParent = strParent.trim();
WScript.Echo ("Value: " + strParent);
Am I being stupid? Any ideas what the problem is?
The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)
JavaScript provides three functions for performing various types of string trimming. The first, trimLeft() , strips characters from the beginning of the string. The second, trimRight() , removes characters from the end of the string. The final function, trim() , removes characters from both ends.
The Trim method removes from the current string all leading and trailing white-space characters. Each leading and trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is " abc xyz ", the Trim method returns "abc xyz".
TrimLeft(), used to remove characters from the beginning of a string. TrimRight(), used to remove characters from the string's end. Trim(), used to remove characters from both ends.
JScript running under the Windows Scripting Host uses an old version of JScript based off of ECMAScript 3.0. The trim function was introduced in ECMAScript 5.0.
You can add trim
to the String class:
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g, '');
};
strParent = " a ";
strParent = strParent.trim();
WScript.Echo ("Value: " + strParent);
C:\>cscript //nologo trim-test.js
Value: a
Use a polyfill, for example this one: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill
This snippet:
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
strParent = " a ";
strParent = strParent.trim();
WScript.Echo ("Value: '" + strParent + "'");
will output
Value: 'a'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With