如何在reactjs中删除字符串中的引号?

问题描述 投票:0回答:1

我是 JavaScript 新手。我有段落并使用 str.split('.') 分割它们。另外,我需要在 split 方法之后从字符串中删除引号。如何消除它们?

我妈妈站起来,从地上拿起一个盒子。 “我们在美国, 符文。他们在这里说英语。你说英语的时间长达 你一直在说挪威语。是时候使用它了。”

我想要这样的结果

我妈妈站起来,从地上拿起一个盒子。我们在美国, 符文。他们在这里说英语。你说英语的时间长达 你一直在说挪威语。是时候使用它了。

javascript reactjs arrays object logic
1个回答
0
投票

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

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"
]
*/
© www.soinside.com 2019 - 2024. All rights reserved.