Contoh 1: Potong String
// program to trim a string
const string = ' Hello World ';
const result = string.trim();
console.log(result);
Keluaran
Hello World
Dalam contoh di atas, trim()
metode yang digunakan untuk memotong string.
Itu trim()
metode menghilangkan spasi putih dari kedua sisi string.
Contoh 2: Memangkas String Menggunakan RegEx
// program to trim a string
function trimString(x) {
let trimValue = x.replace(/^s+|s+$/g,'');
return trimValue;
}
const result = trimString(' Hello world ');
console.log(result);
Keluaran
Hello World
Dalam program di atas, RegEx digunakan dengan replace()
metode untuk memotong string.
/^s+|s+$/g
memeriksa spasi putih di awal dan akhir string.