我有一个字符串,它是我试图使用split方法仅返回该段落的第一句话的段落。我的目标是分别添加第一句话和段落的其余部分。我可以返回第一句话,但我也希望第一句话不再出现在原始data中。在这种情况下,即使我成功地拆分了第一句话,它仍然留在了data中,我怎么能把这两句话分开呢?
例如:
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.
发布于 2020-08-27 00:42:10
字符串是immutable。您在data中对字符串所做的任何方法或任何操作都不会修改字符串-像.split()这样的函数只返回新数据,它们不会改变原始数据。
.split()返回一个包含每个部分的数组。您已经使用第二个参数将其限制为一次拆分,因此第一个参数之后的其余句子不会返回。相反,您可以获得所有的拆分,并在第一次拆分后重新加入其中的拆分。
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)
发布于 2020-08-27 00:37:35
您需要将数组的第二个元素赋给data,以便data包含该值。split()实际上并不修改数组。
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)
发布于 2020-08-27 00:38:15
试试这个。
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)
https://stackoverflow.com/questions/63601918
复制相似问题