可以使用字符串的 'trim()' 方法去除字符串两端的空格,也可以使用正则表达式去除字符串中所有的空格。/n/n示例代码:/n/njs/n// 去除字符串两端的空格/nconst str = ' hello world ';/nconst trimmedStr = str.trim();/nconsole.log(trimmedStr); // 'hello world'/n/n// 去除字符串中所有的空格/nconst strWithSpace = 'hello world';/nconst regex = //s/g;/nconst strWithoutSpace = strWithSpace.replace(regex, '');/nconsole.log(strWithoutSpace); // 'helloworld'/n/n/n在正则表达式中,'//s' 匹配任何空白字符,包括空格、制表符、换行符等,'g' 表示全局匹配。将 '//s' 替换为空字符串即可去除所有空格。

JavaScript去除空格的两种方法

原文地址: https://www.cveoy.top/t/topic/lMMh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录