【问题标题】:How to highlight the first word in every sentence in a string?如何突出显示字符串中每个句子的第一个单词?
【发布时间】:2019-11-22 12:49:07
【问题描述】:

我们有一个任务,我们必须突出显示每个句子中的第一个单词。例如,如果我们有字符串“我喜欢苹果。你喜欢橙子。我们喜欢水果。”我们必须突出显示“I”、“You”、“We”——句号后的第一个词。

谁能帮忙?

【问题讨论】:

  • 高亮是什么意思?
  • 嗨,欢迎来到 SO。如果您为此编写了无法开始工作的代码,那么您来对地方了。只需 edit 问题并将代码的相关部分添加到其中。您需要展示自己的努力,因为 Stack Overflow 不是为我编写代码的服务。另请参阅How to Ask
  • 高亮是什么意思?你自己试过吗?
  • 你是用html和css渲染文本吗?
  • 请提供到目前为止您尝试过的代码

标签: javascript string loops


【解决方案1】:
var words = "I love apples.You love oranges.We love fruit";
var words_array = words.split(".");
var first_words = [];
$(words_array).each(function(k,word){
    first_words.push(word.split(" ")[0]);
});

结果 first_words; (3) [“我”、“你”、“我们”]

【讨论】:

    【解决方案2】:

    只需用“。”分隔您的文本获取所有句子。
    然后再用空格分割,找到要突出显示的每个句子的第一个单词。

    let text = "I love apples. You love oranges. We love fruit.";
    let sentences = text.split('.');
    
    for(let i in sentences) {
    	let sentence = sentences[i].trim();
      
      if(sentence){
      	let firstWhiteSpace = sentence.indexOf(' ');
      	sentence = '*' + sentence.substring(0, firstWhiteSpace) + '*' + sentence.substring(firstWhiteSpace) + '.';
      	console.log(sentence);
      }
      
    }
    <script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>

    【讨论】:

      【解决方案3】:

      希望对你有帮助!

      const texts = 'I love you. You love me. hello world';
      let newText = '';
      
      texts.split('.').forEach(text => {
        const edit = text.trim().split(' ');
        newText +=  `<mark>${edit.shift()}</mark> ${edit.join(' ')}. `;
      });
      document.body.innerHTML = newText.trim();
      

      【讨论】:

        【解决方案4】:

        使用正则表达式,您编写的代码更少。

        let texts = 'I love you. You love me. hello world.';
        texts = texts.replace(/(^|\.\s)([a-z]+)/gi, "$1 <mark>$2</mark>");
        document.body.innerHTML = texts;
        

        【讨论】:

          猜你喜欢
          • 2014-10-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-18
          • 1970-01-01
          • 2012-09-09
          相关资源
          最近更新 更多