在 JavaScript 中去除字符串中的空格
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/26 8:44:17
我们需要编写一个 JavaScript 函数,该函数接受一个字符串并返回一个新字符串,该新字符串包含原始字符串的所有字符,只是删除了空格。
示例
其代码为 −
const str = "This is an example string from which all whitespaces will be
removed";
const removeWhitespaces = str => {
let newStr = '';
for(let i = 0; i < str.length; i++){
if(str[i] !== " "){
newStr += str[i];
}else{
newStr += '';
};
};
return newStr;
};
console.log(removeWhitespaces(str));
输出
控制台中的输出 −
Thisisanexamplestringfromwhichallwhitespaceswillberemoved
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

