Does JScript support string trim method?
Asked Answered
M

3

6

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?

Marker answered 19/7, 2015 at 23:11 Comment(0)
S
6

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.

Swank answered 20/7, 2015 at 7:58 Comment(1)
Thanks v. much Cheran. Back to the drawing board then!Marker
D
5

You can add trim to the String class:

trim-test.js

String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/g, '');
};

strParent = "  a  ";
strParent = strParent.trim();
WScript.Echo ("Value: " + strParent);

Output from cmd.exe

C:\>cscript //nologo trim-test.js
Value: a
Drub answered 23/7, 2015 at 14:18 Comment(0)
D
3

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'
Degenerate answered 17/2, 2016 at 12:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.