Javascript: Есть ли отрицательная функция Slice ()? [Дубликат]

1

Как вы знаете, slice() возвращает нарезанный элемент. Например, "hello".slice(1, 3) возвращает "ell", а не остаток. Мне любопытно это: есть ли какая-либо функция или способ получить остаток от slice()?

  • 0
    .slice(3) вернет подстроку, которая следует за .slice(n, 3) ?
  • 4
    Нет, вы должны вручную 'hello'.slice(0, 1) + 'hello'.slice(3)
Показать ещё 2 комментария
Теги:
slice

1 ответ

4
Лучший ответ

 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"


    
  • 0
    Но как насчет разделения передней части и задней части в массив из 2 элементов?

Ещё вопросы

Сообщество Overcoder
Наверх
Меню