【问题标题】:Does JScript support string trim method?JScript 是否支持字符串修剪方法?
【发布时间】:2015-07-19 23:11:23
【问题描述】:

在使用 JScript 开发 Windows 过程时,某些字符串方法似乎无法正常工作。在这个使用 trim 的示例中,第 3 行会生成运行时错误:

“对象不支持此属性或方法”。

我的代码:

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

我是不是很傻? 任何想法是什么问题?

【问题讨论】:

    标签: windows wsh jscript windows-scripting


    【解决方案1】:

    在 Windows Scripting Host 下运行的 JScript 使用基于 ECMAScript 3.0 的旧版 JScript。 trim 函数是在 ECMAScript 5.0 中引入的。

    【讨论】:

    • 非常感谢 Cheran。那么回到绘图板!
    【解决方案2】:

    您可以将trim 添加到 String 类中:

    trim-test.js

    String.prototype.trim = function()
    {
        return this.replace(/^\s+|\s+$/g, '');
    };
    
    strParent = "  a  ";
    strParent = strParent.trim();
    WScript.Echo ("Value: " + strParent);
    

    cmd.exe 的输出

    C:\>cscript //nologo trim-test.js
    Value: a
    

    【讨论】:

      【解决方案3】:

      使用 polyfill,例如这个: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill

      这个sn-p:

      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 + "'");
      

      会输出

      Value: 'a'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多