Giả sử chuỗi có khoảng trắng:
var fullName=" John Smith ";
Sử dụng replace() với Regex để loại bỏ khoảng trắng đầu và cuối.
Ví dụ
function removeSpacesAtTheBeginningAndTheEnd(name) { return name.toString().replace(/^\s+|\s+$/g,''); } var fullName=" John Smith "; var valueAfterRemovingSpace=removeSpacesAtTheBeginningAndTheEnd(fullName) console.log(valueAfterRemovingSpace);Chạy: node fileName.js. File demo208.js.
Kết quả
PS C:\Users\Amit\javascript-code> node demo208.js John Smith