解如何在 JavaScript 中輕松地在字符串的字符之間添加空格。
在本文中,我們將學(xué)習(xí)如何在 JavaScript 中輕松地在字符串的字符之間包含空格。
1. String split() 和 Split join() 方法
要在字符串的字符之間添加空格,請(qǐng)?jiān)谧址险{(diào)用 split() 方法以獲取字符數(shù)組,然后在數(shù)組上調(diào)用 join() 方法以使用空格分隔符連接字符。
例如:
function addSpace(str) {
return str.split('').join(' ');
}const str1 = 'coffee';
const str2 = 'banana';console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
String split() 方法使用指定的分隔符將字符串拆分為子字符串?dāng)?shù)組。
const str1 = 'coffee,milk,tea';
const str2 = 'sun-moon-star';console.log(str1.split(',')); // [ 'coffee', 'milk', 'tea' ]
console.log(str2.split('-')); // [ 'sun', 'moon', 'star' ]
通過(guò)使用空字符串 ('') 作為分隔符,我們將所有字符串字符拆分為單獨(dú)的數(shù)組元素。
const str1 = 'coffee';
const str2 = 'banana';// Passing an empty string ('') to the split method// [ 'c', 'o', 'f', 'f', 'e', 'e' ]
console.log(str1.split(''));// [ 'b', 'a', 'n', 'a', 'n', 'a' ]
console.log(str2.split(''));
String join() 方法將數(shù)組中的每個(gè)字符串與分隔符組合在一起。 它返回一個(gè)包含連接數(shù)組元素的新字符串。
const arr = ['a', 'b', 'c', 'd'];console.log(arr.join(' ')); // a b c d
console.log(arr.join('-')); // a-b-c-d
console.log(arr.join('/')); // a/b/c/d
因此,將空格字符傳遞給 join() 會(huì)在結(jié)果串聯(lián)中用空格分隔字符。
在某些情況下,字符串已經(jīng)在某些字符之間包含空格。 在這種情況下,我們的方法會(huì)在字符之間添加更多空格。
function addSpace(str) {
return str.split('').join(' ');
}// These strings have spaces between some characters
const str1 = 'co ffee';
const str2 = 'bana na';console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
這是因?yàn)榭崭?(' ') 也是一個(gè)字符,就像一個(gè)字母,調(diào)用 split() 會(huì)使其成為數(shù)組中的一個(gè)單獨(dú)元素,該元素將與其他空格組合。
// These strings have spaces between some characters
const str1 = 'co ffee';
const str2 = '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(''));
如果我們想避免字符的多個(gè)間距,我們可以在 split() 和 join() 之間插入對(duì) filter() 方法的調(diào)用。
function addSpace(str) {
return str
.split('')
.filter((item) => item.trim())
.join(' ');
}// The strings have spaces between some characters
const str1 = 'co ffee';
const str2 = 'bana na';console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
Array filter() 方法返回一個(gè)新數(shù)組,該數(shù)組僅包含原始數(shù)組中的元素,傳遞給 filter() 的測(cè)試回調(diào)函數(shù)為其返回真值。 對(duì)空格 (' ') 調(diào)用 trim() 會(huì)產(chǎn)生一個(gè)空字符串 (''),這在 JavaScript 中不是真值。 因此,從 filter() 返回的結(jié)果數(shù)組中排除了空格。
小費(fèi)
在 JavaScript 中,只有六個(gè)假值:false、null、undefined、0、''(空字符串)和 NaN。 其他所有值都是真實(shí)的。
2. for...of 循環(huán)
對(duì)于更命令式的方法,我們可以使用 JavaScript for...of 循環(huán)在字符串的字符之間添加一個(gè)空格。
function addSpace(str) {
// Create a variable to store the eventual result
let result = ''; for (const char of str) {
// On each iteration, add the character and a space
// to the variable
result += char + ' ';
} // Remove the space from the last character
return result.trimEnd();
}const str1 = 'coffee';
const str2 = 'banana';console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
為了處理前面討論的場(chǎng)景,其中字符串在某些字符之間有空格,請(qǐng)?jiān)诿看蔚淖址险{(diào)用 trim(),并添加一個(gè) if 檢查以確保它是真實(shí)的,然后將它和空格添加到累積結(jié)果中:
function addSpace(str) {
// Create a variable to store the eventual result
let result = ''; for (const char of str) {
// 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 truthy
if (char.trim()) {
result += char + ' ';
}
} // Remove the space from the last character
return result.trimEnd();
}const str1 = 'co ffee';
const str2 = 'bana na';console.log(addSpace(str1)); // c o f f e e
console.log(addSpace(str2)); // b a n a n a
關(guān)注七爪網(wǎng),獲取更多APP/小程序/網(wǎng)站源碼資源!
除字符串左右兩端的空格, 在PHP和Golang里面可以輕松地使用 trim、ltrim 或 rtrim, 但在JavaScript中卻沒(méi)有這三個(gè)內(nèi)置方法, 需要手工編寫(xiě)。
下面的實(shí)現(xiàn)方法是用到了正則表達(dá)式, 效率不錯(cuò), 并把這三個(gè)方法加入String對(duì)象的內(nèi)置方法中去。
寫(xiě)成類(lèi)的方法格式如下:(str.trim();)
<script type="text/javascript">
//刪除左右兩端的空格
String.prototype.trim=function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
//刪除左邊的空格
String.prototype.ltrim=function(){
return this.replace(/(^\s*)/g,"");
}
//刪除右邊的空格
String.prototype.rtrim=function(){
return this.replace(/(\s*$)/g,"");
}
</script>
寫(xiě)成函數(shù)可以這樣:(trim(str))
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。