在ReactJS中从字符串中移除引号:指南
P粉165522886
P粉165522886 2023-09-17 23:46:44
0
1
550

我刚开始学习JavaScript。我有一个段落,使用str.split('.')将其分割。此外,我需要在分割后的字符串中去掉引号。如何去掉它们?

我的妈妈站起来,从地上拿起一个盒子。“我们在美国,Rune。他们在这里讲英语。你一直在说英语,就像你一直在说挪威语一样。是时候用英语了。”

我希望结果如下:

我的妈妈站起来,从地上拿起一个盒子。我们在美国,Rune。他们在这里讲英语。你一直在说英语,就像你一直在说挪威语一样。是时候用英语了。

P粉165522886
P粉165522886

全部回复(1)
P粉680087550

在拆分数组之前,去除所有引号会更容易。

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之后循环/映射每个句子。

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()

result = sentences.map(sentence => sentence.replace(/“|”/g,'')).filter(sentence => sentence);

要去除空格,您还可以使用.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"
]
*/
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!