【问题标题】:Javascript : Is there Slice()'s negative function? [duplicate]Javascript:有 Slice() 的负函数吗? [复制]
【发布时间】:2018-09-19 04:49:59
【问题描述】:

如您所知, slice() 返回切片的项目。例如,"hello".slice(1, 3) 返回“ell”,而不是余数。我很好奇的是:有没有什么函数或方法可以获取 slice() 的剩余部分?

【问题讨论】:

  • .slice(3) 将返回 .slice(n, 3)? 后面的子字符串?
  • 不行,你必须手动连接'hello'.slice(0, 1) + 'hello'.slice(3)
  • 单线:const removeSection = (string, from=0, to=string.length) => string.slice(0, from) + string.slice(to); 用法:removeSection('hello', 1, 3)
  • 有什么更干净简单的方法吗?

标签: javascript slice


【解决方案1】:

 String.prototype.remainderOfSlice = function(begin, end) {

    begin = begin || 0
    end = (end === undefined) ? this.length : end 

    if (this.slice(begin, end) === '') return this + ''
    return this.slice(0, begin) + this.slice(end) 
 }



console.log("hello".slice()) // "hello"
console.log("hello".remainderOfSlice()) // ""

console.log("hello".slice(-3)) // "llo"
console.log("hello".remainderOfSlice(-3)) // "he"

console.log("hello".slice(-3, 0)) // ""
console.log("hello".remainderOfSlice(-3, 0)) // "hello"

console.log("hello".slice(1, 3)) // "el"
console.log("hello".remainderOfSlice(1, 3)) // "hlo"


    

【讨论】:

  • 但是如何将前半部分和后半部分拆分为一个 2 元素数组?
猜你喜欢
  • 1970-01-01
  • 2012-02-06
  • 1970-01-01
  • 2011-04-30
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-27
相关资源
最近更新 更多