JavaScript 程序:修剪字符串
要理解这个示例,你应该具备以下 JavaScript 编程 主题的知识:
示例 1:修剪字符串
// 程序修剪字符串
const string = " Hello World ";
const result = string.trim();
console.log(result);
输出
Hello World
在上述示例中,使用了 trim()
方法来修剪字符串。
trim()
方法移除字符串两边的空白字符。
示例 2:使用正则表达式修剪字符串
// 程序修剪字符串
function trimString(x) {
let trimValue = x.replace(/^\s+|\s+$/g, "");
return trimValue;
}
const result = trimString(" Hello world ");
console.log(result);
输出
Hello World
在上述程序中,使用正则表达式与 replace()
方法来修剪字符串。
/^\s+|\s+$/g
检查字符串开始和结束处的空白字符。