所以我有一个字符串(段落(数组,每个字符串中的第一个短语表示标题。例如。。。
[
"The Lion, the Witch and the Wardrobe n There was once a lion, a
witch and a wardrobe. The End"
]
如您所见,标题由换行符分隔 n
.有没有一种方法可以用来在换行符之前抓取字符串的一部分并将其存储在变量中?
我有大量这样的字符串,所以我正在寻找一种不仅与"狮子,女巫和衣柜"相匹配的解决方案
提前感谢伙计们。
我需要的结果...
let 标题 = [ "狮子、女巫和衣柜"、"示例"、"示例" ]
let body = ["曾经是...","示例","示例"]
您可以拆分字符串,然后像这样提取第一个元素:
const phrase = [
"The Lion, the Witch and the Wardrobe n There was once a lion, a witch and a wardrobe. The End"
]
const getHeader = ([header, ...rest]) => header
const result = getHeader(phrase[0].split('n'))
console.dir(result)
编辑后,我看到您还想要正文,您可以这样做:
const phrase = [
"The Lion, the Witch and the Wardrobe n There was once a lion, a witch and a wardrobe. The End"
]
const getHeader = ([header, ...body]) => ({
header: [header],
body,
})
const result = getHeader(phrase[0].split('n'))
console.dir(result)
加上额外的猜测:
从你的问题来看,你有一个文本数组,并希望每个数组输出两个数组;一个标题数组和一个主体数组。这可能是这样:
const texts = [
"The Lion, the Witch and the Wardrobe n There was once a lion, a witch and a wardrobe. The End",
"The BiblenIn the beginning, God created the heavens and earth"
]
const getHeaderAndBody = ([header, ...body]) => ({
header: [header],
body,
});
const mergeHeadersAndBodies = (prev, curr) => ({
headers: [
...(prev.headers || []),
...curr.header
],
bodies: [
...(prev.bodies || []),
...curr.body
]
})
const splitToNewLines = text => text.split('n')
const mapToHeadersAndBodies = input => input
.map(splitToNewLines)
.map(getHeaderAndBody)
.reduce(mergeHeadersAndBodies, {})
const result = mapToHeadersAndBodies(texts)
console.dir(result)
function myFunction() {
var str = "The Lion, the Witch and the Wardrobe n There was once a lion, a n witch and a wardrobe. The End";
var res = str.split("n");
alert(res);
}
尝试使用javascript拆分函数。
仅使用数组的映射函数和字符串的子字符串函数
let body = ["a n b","c n d","e n f"]
let headers = arrayOfStrings.map(s => s.substring(0,s.indexOf(" n ")))
换行符应该只是 末尾没有 \,否则会导致问题
你可以像其他人提到的那样使用Javascript的split
方法。
如果要解析的所有字符串的格式相同,即 {header, , body},则使用以下代码。它将每个字符串分成两个,然后将每个部分存储在单独的变量中。
const phrases = [
"The Lion, the Witch and the Wardrobe n There was once a lion, a witch and a wardrobe. The End",
"This is the header n this is the body",
"This is another header n this is another body"
]
let headers = []
let bodies = []
phrases.forEach(phrase => {
let split = phrase.split('n')
headers.push(split[0])
bodies.push(split[1])
})
console.log(headers)
console.log(bodies)