DEV Community

ahoNerd
ahoNerd

Posted on • Originally published at ahonerd.com on

How to Remove Last Character from a String in JavaScript

Cara untuk menghilangkan karakter terakhir dari sebuah string dalam JavaScript.

slice() Method

Berikut ini adalah contoh penggunaan slice():

const string1 = 'Aho dakara'
const string2 = string1.slice(0, -7)
const string3 = string1.slice(5, -1)
const string4 = string1.slice(5, 9)
const string5 = string1.slice(4)
const string6 = string1.slice(99)

console.log(string1.length) // 10
console.log(string2) // "Aho"
console.log(string3) // "akar"
console.log(string4) // "akar"
console.log(string5) // "dakara"
console.log(string6) // ""
Enter fullscreen mode Exit fullscreen mode

Berikut ini adalah contoh penggunaan slice() untuk menghilangkan karakter terakhir dari sebuah string:

const url = 'https://ahonerd.com/'
const path = '/about'

console.log(url + path) // https://ahonerd.com//about

const url1 = url.slice(0, -1)

console.log(url1 + path) // https://ahonerd.com/about
Enter fullscreen mode Exit fullscreen mode

Syntax

string.slice(start)
string.slice(start, end)
Enter fullscreen mode Exit fullscreen mode

Parameters

  • start

Index posisi karakter pertama yang akan diikutsertakan pada hasil (returned substring)

  • end

Index posisi karakter pertama yang tidak diikutsertakan pada hasil (returned substring).

Parameter ke-2 ini sifatnya optional.

Return value

Bagian string yang diekstrak type: string

Reference

developer.mozilla.org

w3schools.com

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay