JavaScript 字符串截断程序

要理解此示例,您应了解以下 JavaScript 编程 主题


示例 1:截断字符串

// program to trim a string

const string = '      Hello World       ';

const result = string.trim();

console.log(result);

输出

Hello World

在上面的示例中,使用 trim() 方法来截断字符串。

trim() 方法会删除字符串两端的空格。


示例 2:使用正则表达式截断字符串

// 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

在上面的程序中,使用正则表达式和 replace() 方法来截断字符串。

/^\s+|\s+$/g 检查字符串开头和结尾的空格。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战