functionaddSpace(str) {
returnstr.split('').join(' ');
}
conststr1='coffee';
conststr2='banana';
console.log(addSpace(str1)); // c o f f e econsole.log(addSpace(str2)); // b a n a n a
functionaddSpace(str) {
returnstr.split('').join(' ');
}
// These strings have spaces between some charactersconststr1='co ffee';
conststr2='bana na';
console.log(addSpace(str1)); // c o f f e econsole.log(addSpace(str2)); // b a n a n a
// These strings have spaces between some charactersconststr1='co ffee';
conststr2='bana na';
// The space characters are separate elements of the// array from split()/** * [ 'c', 'o', ' ', ' ', 'f', 'f', 'e', 'e'] */console.log(str1.split(''));
/** * [ 'b', 'a', 'n', 'a', ' ', ' ', 'n', 'a'] */console.log(str2.split(''));
functionaddSpace(str) {
returnstr
.split('')
.filter((item) =>item.trim())
.join(' ');
}
// The strings have spaces between some charactersconststr1='co ffee';
conststr2='bana na';
console.log(addSpace(str1)); // c o f f e econsole.log(addSpace(str2)); // b a n a n a
functionaddSpace(str) {
// Create a variable to store the eventual resultletresult='';
for (constcharofstr) {
// On each iteration, add the character and a space// to the variableresult+=char+' ';
}
// Remove the space from the last characterreturnresult.trimEnd();
}
conststr1='coffee';
conststr2='banana';
console.log(addSpace(str1)); // c o f f e econsole.log(addSpace(str2)); // b a n a n a
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
要处理前面讨论的情况,其中字符串在某些字符之间有空格,请在每次迭代的字符上调用 trim(),并添加一个 if 检查以确保它是真实的,然后再将它和空格添加到累积结果中:
functionaddSpace(str) {
// Create a variable to store the eventual resultletresult='';
for (constcharofstr) {
// On each iteration, add the character and a space// to the variable// If the character is a space, trim it to an empty// string, then only add it if it is truthyif (char.trim()) {
result+=char+' ';
}
}
// Remove the space from the last characterreturnresult.trimEnd();
}
conststr1='co ffee';
conststr2='bana na';
console.log(addSpace(str1)); // c o f f e econsole.log(addSpace(str2)); // b a n a n a