JavaScript 如何用单个空格替换多个空格
在本文中,我们将看到如何在JavaScript中用单个空格替换多个空格。
有两种方法可以在JavaScript中用单个空格替换多个空格。
- 使用replace()方法
- 使用trim()、split()、join()方法
方法1:使用replace()方法
我们将使用replace()方法在JavaScript中用单个空格替换多个空格。首先,我们使用正则表达式/\s+/g来全局匹配一个或多个空格,并将其替换为“ ”。
示例:
Javascript
// String containing multiple spaces
let str = " Welcome to Geeks for Geeks ";
// Remove multiple spaces with single space
let newStr = str.replace(/\s+/g, ' ');
// Display the result
console.log(newStr);
输出
Welcome to Geeks for Geeks
方法2: 使用trim()、split()和join()方法
首先,我们将使用 trim() 方法来去除开头和结尾的额外空格,然后使用split()方法将字符串按照空格拆分,最后使用join()方法使用单个空格将拆分后的字符串连接起来。
示例:
Javascript
// String containing multiple spaces
let str = " Welcome to Geeks for Geeks ";
// Replace multiple spaces with single space
let newStr = str.trim().split(/[\s,\t,\n]+/).join(' ');
// Display the result
console.log(newStr);
输出
Welcome to Geeks for Geeks