示例 1: 修剪字符串
// program to trim a string const string = ' Hello World '; const result = string.trim(); console.log(result);
输出
Hello World
在上面的例子中,
trim()
方法用于修剪字符串。
trim()
方法删除字符串两侧的空格。
示例 2: 使用 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);
输出
Hello World
在上面的程序中,RegEx 与
replace()
方法一起使用来修剪字符串。
/^\s+|\s+$/g
检查字符串开头和结尾的空格。