【问题标题】:displays the first 4 words of a phrase in html在 html 中显示短语的前 4 个单词
【发布时间】:2016-04-11 17:11:55
【问题描述】:

我有一个很长的短语,我想显示前 4 个单词。

示例:

The style of this paper is a combination of an external stylesheet, and internal style.

变成这样:

这个风格……

【问题讨论】:

标签: javascript css angularjs html


【解决方案1】:

您可以为此使用正则表达式。它需要前四个单词并添加一些点,

var text = 'The style of this paper is a combination of an external stylesheet, and internal style.';
document.write(text.replace(/^((\w*\W*){0,4}).*/, '$1...'));

【讨论】:

    【解决方案2】:

    您可以创建一个函数,从元素的文本中返回前 N 个单词。例如:

    function firstWords(wrapperId, wordCount) {
        var element = document.getElementById(wrapperId);
        var textArray = element.textContent.split(/\s/);
        if(textArray.length >= wordCount) {
            return textArray.slice(0, wordCount).join(" ");
        } else {
            return textArray.join(" ");
        }
    }
    

    如果包装器的 ID 为“foo”,例如

    <div id="foo">This is a sample text!</div>
    

    你可以打电话

    console.log(firstWords("foo", 4));
    

    【讨论】:

      【解决方案3】:

      使用

      strArr[] = str.split(" ");
      

      str[0], str[1], str[2], str[3] 是你想要使用的结果。

      【讨论】:

        猜你喜欢
        • 2019-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多