简体   繁体   中英

How can I remove the first and last characters from a string?

Example :

let a = 'hello' 

Select the first and last characters from the string and remove them.

console.log(a);

//expected output 

ell

You could use slice . https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

In your case, this should work:

a.slice(1, -1);

This can also help:

let a = 'hello'
a.substring(1, a.length - 1)

For more details: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/substring

Use the javascript slice function.

a.slice(1, a.length)

Look up the javascript slice function.

Avoiding splice, slice, substring...

const word = 'hello'
const filtered =
  word
  .split('')
  .filter((x, i) => !(i === 0 || i === word.length - 1))
  .join('');

console.log(filtered)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM