84669 人學習
152542 人學習
20005 人學習
5487 人學習
7821 人學習
359900 人學習
3350 人學習
180660 人學習
48569 人學習
18603 人學習
40936 人學習
1549 人學習
1183 人學習
32909 人學習
我剛開始學習JavaScript。我有一個段落,使用str.split('.')將其分割。此外,我需要在分割後的字串中去掉引號。如何去除它們?
我的媽媽站起來,從地上拿起一個盒子。 「我們在美國,Rune。他們在這裡講英語。你一直在說英語,就像你一直在說挪威語一樣。是時候用英語了。」
我希望結果如下:
我的媽媽站起來,從地上拿起一個盒子。我們在美國,Rune。他們在這裡講英語。你一直在說英語,就像你一直在說挪威語一樣。是時候用英語了。
在拆分數組之前,移除所有引號會更容易。
const paragraph = `My mamma stood up and lifted a box off the ground. “We’re in America, Rune. They speak English here. You’ve been speaking English for as long as you’ve been speaking Norwegian. It’s time to use it.”`.replace(/“|”/g,''); console.log(paragraph); // "My mamma stood up and lifted a box off the ground. We’re in America, Rune. They speak English here. You’ve been speaking English for as long as you’ve been speaking Norwegian. It’s time to use it."
如果您堅持先拆分數組,那麼您應該在.split之後循環/映射每個句子。
.split
const sentences = `My mamma stood up and lifted a box off the ground. “We’re in America, Rune. They speak English here. You’ve been speaking English for as long as you’ve been speaking Norwegian. It’s time to use it.”`.split('.'); const result = result = sentences.map(sentence => sentence.replace(/“|”/g,'')); console.log(result); /* [ "My mamma stood up and lifted a box off the ground", " We’re in America, Rune", " They speak English here", " You’ve been speaking English for as long as you’ve been speaking Norwegian", " It’s time to use it", "" ]; */
如您所見,最後一個項目是空字串。要移除它,您也可以使用.filter()。
.filter()
result = sentences.map(sentence => sentence.replace(/“|”/g,'')).filter(sentence => sentence);
要移除空格,您也可以使用.trim()。
.trim()
因此,將所有這些放在一起:
const sentences = `My mamma stood up and lifted a box off the ground. “We’re in America, Rune. They speak English here. You’ve been speaking English for as long as you’ve been speaking Norwegian. It’s time to use it.”`.split('.'); const result = sentences .map(sentence => sentence.replace(/“|”/g, '').trim()) .filter(sentence => sentence); console.log(result); /* [ "My mamma stood up and lifted a box off the ground", "We’re in America, Rune", "They speak English here", "You’ve been speaking English for as long as you’ve been speaking Norwegian", "It’s time to use it" ] */
在拆分數組之前,移除所有引號會更容易。
如果您堅持先拆分數組,那麼您應該在
.split
之後循環/映射每個句子。如您所見,最後一個項目是空字串。要移除它,您也可以使用
.filter()
。要移除空格,您也可以使用
.trim()
。因此,將所有這些放在一起: