【问题标题】:How can I return a specific amount of words from a JSON object?如何从 JSON 对象返回特定数量的单词?
【发布时间】:2021-08-04 19:49:00
【问题描述】:

我想显示最多 13 个单词作为每个笔记中所写内容的预览,如果有更多文本,则将该文本替换为三个点。

例如:This is a user saved note and I'm limited to displaying thirteen words...

我目前拥有的只是对JSON对象的完整解析,无论它有多大,但是我需要限制长度。

我尝试过使用 Javascript 字符串方法,但没有成功。

 return (
        <div className="notes">
            <div className="notes_header">
                <p>You have {numberOfNotes} notes</p>
            </div>

            <div>
               {notes.map((val) => {
                   return <div key={val.id} onClick={() => Logic.selectNote(val.note, val.id)}><ReactQuill className="note" value={JSON.parse(val.note)} readOnly={true}  /></div>
               })}
            </div>
        </div>
    )
}

这是我解析val.note后的输出

0: {insert: "This is a user note.\n"}

【问题讨论】:

  • 在空白处拆分字符串,最多占用结果数组的 13 个元素,用空格重新连接它们,附加省略号。
  • 您提供的代码与问题无关,这是一个纯字符串操作问题。渲染无关紧要。
  • 恕我直言,这个问题太宽泛了,因此不清楚您实际上在问什么。您是在问如何解析 JSON 直到一个特定的分隔符?您是在问如何截断字符串?你想用更高效的功能替换JSON.parse(val.note)吗? val.note 是什么?
  • @jarmod 我刚刚查看了一下,它并不完全相关,因为我无法将字符串方法应用于解析的 JSON 对象。我试过了,但我不知道为什么。

标签: javascript json reactjs string react-native


【解决方案1】:

假设val.note 是一个简单的字符串:

const maxWords = 13
const note = JSON.parse(val.note)
words = note.split(/(?=\W)/) // 1
const notePreview = words.length > maxWords ? [...words.slice(0, maxWords), '...'].join('') : note // 2

在第 1 行中,您在每个单词边界之前拆分注释文本((?=) 是一个积极的前瞻正则表达式模式)。在第 2 行中,您检查这是否给了您比您想要的更多的单词。如果是,则使用所需的单词数创建一个新数组,添加省略号并将其连接到字符串。如果没有,您只需使用注释文本。

【讨论】:

    【解决方案2】:

    这是一个可以截断或剪切文本的函数。它在给定数量的单词后剪切输入文本并添加“...”

    /**
     * Generates teaser text for your note by limiting it to a certain number of words
     * @param {string} note     Your note or input text
     * @param {number} maxWords The max number of words to allow in the output
     **/
    const clipTextByWordCount = (note, maxWords) => {
        if(note.indexOf(' ') === -1) {
            return note;
        }
        
        let words = (note.split(' ')).filter((w, i) => i < maxWords);
        return words.join(' ') + '...';
    };
    

    首先你想使用JSON.parse(jsonString)方法将你的json从一个字符串解析成一个对象,然后你想从这个解析的对象中获取完整的注释文本。

    如果我可以从您的示例代码中分辨出您的 JSON 的结构,我可能会更有帮助,但根据您的示例并不清楚。

    一旦您知道如何从解析的对象中检索完整的注释文本,您希望将该完整的注释文本传递到 clipTextByWordCount(text, 10) 以将截断的文本显示给用户。

    这是一个使用示例:

    const noteJson = "{\"id\": 5, \"val\": \"this is a whole bunch of words that I am typing for you to read right now\"}";
    const val = JSON.parse(noteJson);
    let displayText = clipTextByWordCount(val.note, 10); // "this is a whole bunch of words that I am..."
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-03
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多