19 May 2021

Removing first and last character from a string in JavaScript

 

Using slice method

let str = '/hello/';

//slice starts from index 1 and ends before last index
console.log(str.slice(1,-1));

//output --> 'hello'

Note: Negative index -1 is equivalent to str.length-1 in slice method.

Using substring method

let str = '/hello/';

console.log(str.substring(1,str.length-1));

//output --> 'hello'

Using both slice and substring methods

let str = '/hello/';

console.log(str.substring(1).slice(0,-1));

//output --> 'hello'

Using replace method

let str = '/hello/';

console.log(str.replace(/^(.)|(.)$/g,''));

//output --> 'hello'

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang