Javascript:使用 "this"修改字符串的 [[PrimitiveValue]]

标签 javascript

我遇到了一个需要对 JavaScript 原语有深入了解的人的情况。

问题:我想扩展 String 并添加一个名为“extract”的函数,该函数的功能与“substr”类似,但在返回子字符串的过程中,它也从原始字符串中删除了子字符串。

例如,以下内容不起作用。

if (!String.prototype.extract) {
  String.prototype.extract = function (delimiter) {
    var copyStr = "";
    var i = this.indexOf(delimiter);
    if (i >= 0) {
      copyStr = this.substr(0, i);
      console.log(this); <<-- "String" 

      //This line doesn't work, don't know what [[PrimitiveValue]] is.
      this.[[PrimitiveValue]] = this.replace(copyStr + delimiter,"");      

      // Nor this line works.  Can't modify 'this'
      this = this.replace(copyStr + delimiter, ""); 
    }
    return copyStr;
  }
}

然后我可以这样调用:

var str = "abcdef";
var str2 = str.extract('c');  
console.log(str); <<-- this should be 'def'
console.log(str2); <<-- this should be 'abc'

我可以编写一个独立的函数,如下所示,它返回子字符串和修改后的原始字符串,但这不是重点。

function extractSubString(originalStr, delimiter) {
    var copyStr = "";
    var i = originalStr.indexOf(delimiter);
        if (i >= 0) {
            copyStr = originalStr.substr(0, i);
            originalStr = original.replace(copyStr + delimiter, "");
        }  
    return copyStr;
}

有什么想法吗?

谢谢。

最佳答案

but in the process of returning the sub-string, it also removes the sub-string from the original string.

字符串是不可变的,这意味着它们的值不能以任何方式修改。

关于Javascript:使用 "this"修改字符串的 [[PrimitiveValue]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34093887/

相关文章:

javascript - 注销后禁用浏览器 'Back' 按钮?

javascript - 使用纬度和经度从链接启动谷歌地图方向的网络应用程序

javascript - 使用点击刷新表体的最佳方法是什么

javascript - 将 MySQL 查询转换为等效的 Knex QueryBuilder 语法?

javascript - 使用 $compile 以编程方式添加指令并从范围传递数据,

javascript - 存储在对象属性中的数组的解构赋值

javascript - 函数提前触发

javascript - Mongoose 从远程服务器获取外部数据

javascript - 不可靠的点击项 Selenium WebdriverJS

javascript - Reactjs - 将相同的 Prop 传递给多个子组件