从段落中获取短语的JavaScript方法

时间:2019-04-05 12:24:14

标签: javascript

因此,我有一个字符串数组(段落),每个字符串中的第一个短语代表标题。例如...

[
  "The Lion, the Witch and the Wardrobe \n\ There was once a lion, a 
  witch and a wardrobe. The End"
]

如您所见,标头由换行符\n\分隔。有没有一种方法可以在换行之前获取字符串的一部分并将其存储在变量中?

我有很多这样的琴弦,所以我正在寻找一种不仅仅与“狮子,女巫和衣柜”匹配的解决方案

先谢谢大家。

我需要的结果...

let headers = [“狮子,女巫和衣柜”,“示例”,“示例”]

let body = [“曾经是一个...”,“示例”,“示例”]

4 个答案:

答案 0 :(得分:2)

您可以分割字符串,然后像这样提取第一个元素:

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 Bible\n\In 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)

答案 1 :(得分:0)

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拆分功能。

答案 2 :(得分:0)

只需使用数组的map函数和字符串的substring函数

let body = ["a \n\ b","c \n\ d","e \n\ f"]
let headers = arrayOfStrings.map(s => s.substring(0,s.indexOf(" \n\ ")))

和换行符应该只是\ n末尾没有\,否则会引起问题

答案 3 :(得分:0)

您可以像其他人一样使用Javascript的split方法。

如果您要解析的所有字符串的格式都相同,即{header,\ n,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)