首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拆分字符串的第一句话

拆分字符串的第一句话
EN

Stack Overflow用户
提问于 2020-08-27 00:31:56
回答 4查看 67关注 0票数 0

我有一个字符串,它是我试图使用split方法仅返回该段落的第一句话的段落。我的目标是分别添加第一句话和段落的其余部分。我可以返回第一句话,但我也希望第一句话不再出现在原始data中。在这种情况下,即使我成功地拆分了第一句话,它仍然留在了data中,我怎么能把这两句话分开呢?

例如:

代码语言:javascript
复制
 const data = "The amount spent on gasoline continues to be a large expense to many individuals. The average amount spent on gasoline per year is $2000. This number can easily change as the price of gasoline is rapidly changing."

let firstSentence = data.split('\.', 1)[0];

console.log(firstSentence)

console.log(data)

我的预期结果是:

first sentence: "The amount spent on gasoline continues to be a large expense to many individuals."

data: "The average amount spent on gasoline per year is $2000. This number can easily change as the price of gasoline is rapidly changing.

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-08-27 00:42:10

字符串是immutable。您在data中对字符串所做的任何方法或任何操作都不会修改字符串-像.split()这样的函数只返回新数据,它们不会改变原始数据。

.split()返回一个包含每个部分的数组。您已经使用第二个参数将其限制为一次拆分,因此第一个参数之后的其余句子不会返回。相反,您可以获得所有的拆分,并在第一次拆分后重新加入其中的拆分。

代码语言:javascript
复制
 const data = "The amount spent on gasoline continues to be a large expense to many individuals. The average amount spent on gasoline per year is $2000. This number can easily change as the price of gasoline is rapidly changing."

let sentences = data.split('\.');
let firstSentence = sentences.shift(); //remove and return first element
let rest = sentences.join('.').trim(); //undo split and trim the space

console.log(firstSentence)
console.log(rest)

票数 4
EN

Stack Overflow用户

发布于 2020-08-27 00:37:35

您需要将数组的第二个元素赋给data,以便data包含该值。split()实际上并不修改数组。

代码语言:javascript
复制
let data = "The amount spent on gasoline continues to be a large expense to many individuals. The average amount spent on gasoline per year is $2000. This number can easily change as the price of gasoline is rapidly changing."; // Original data

const arr = data.split(/\./); // Split data

let firstSentence = arr[0]; // Set firstSentence to the first item of array

arr.shift(); // Remove first item

data = arr.join('. '); // Set data to the rest of the array

console.log(firstSentence)

console.log(data)

票数 0
EN

Stack Overflow用户

发布于 2020-08-27 00:38:15

试试这个。

代码语言:javascript
复制
let data = "The amount spent on gasoline continues to be a large expense to many individuals. The average amount spent on gasoline per year is $2000. This number can easily change as the price of gasoline is rapidly changing."

let firstSentence = data.split('\.', 1)[0];

data = data.replace(firstSentence + '. ', '');
console.log(firstSentence)

console.log(data)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63601918

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档