Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JScript support string trim method?

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?

like image 579
Andrew Shep Avatar asked Jul 19 '15 23:07

Andrew Shep


People also ask

Is there a trim function in JavaScript?

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.)

How do you trim down a string in JavaScript?

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.

Is trim a string method?

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".

How do you trim a string at the beginning or ending in JavaScript?

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.


Video Answer


3 Answers

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.

like image 53
Cheran Shunmugavel Avatar answered Oct 06 '22 21:10

Cheran Shunmugavel


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
like image 21
Chad Nouis Avatar answered Oct 06 '22 23:10

Chad Nouis


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'
like image 36
Alessandro Jacopson Avatar answered Oct 06 '22 21:10

Alessandro Jacopson