将两个句子拆分为单词和字符并单独显示

Split two sentences into words and characters and show them individually

请帮我把两个句子拆分成一个单词和字符数组,并分别显示它们。

我的输入字符串是这样的:

If you didn't cry, I will give you sweets. Then I will give you home-made cakes.

我目前所做的如下:

$(function() {
  generateWords();

  function generateWords() {
    $("#splitedWords").html("");
    var Input = "If you didn't cry, I will give you sweets. Then I will give you home-made cakes.";
    var outputArray = Input.split(/\s+/); // for spliting each word
    // for printing the sorted words inside a button
    for (var i = 0; i < outputArray.length; i++) {
      $("#splitedWords").append($('<span>' + outputArray[i] + '</span><br/>'));
    }

  }
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>

<body>
  <h4>Input</h4>
  <p>If you didn't cry, I will give you sweets. Then I will give you home-made cakes.</p>
  <h4>O/P required <small>( Want to split words, dot, comma, hyphen, semicolon etc into an array)</small></h4>
  <p>
    var outputArray = [ "If", "you", "didn't", "cry", ",", "I", "will", "give", "you", "sweets", ".", "Then", "I", "will", "give", "you", "home-made", "cakes", "." ];
  </p>
  <h4>Actual O/P</h4>
  <p id="splitedWords"></p>
</body>

</html>

我走的路对吗?感谢您的帮助:)

您要做的是将文本拆分为 标记 。如果你搜索,你会找到这个问题的无限解决方案,因为这是大多数语言解析器为了进一步分析文本所做的。我强烈建议这样做,这是一些需要熟悉的有用的东西。

你可以用很多方法来做到这一点,正则表达式就是其中一种,但不是最简单的方法。

[!#%&\'*+,\-./:;<=>?@\\^_\`|~](?!\w)|[\"\)\(\]\[{}]|[^\s]*?(?=[!\"\#%&\'()*+,\-./:;<=>?@[\\]^_\`{|}~]?(?:\s|$))

我当场想到的是所有匹配是你所有的代币,如图HERE ,只需将它们放入数组即可。

array = yourstring.match(/[!#%&\'*+,\-./:;<=>?@\\^_\`|~](?!\w)|[\"\)\(\]\[{}]|[^\s]*?(?=[!\"\#%&\'()*+,\-./:;<=>?@[\\]^_\`{|}~]?(?:\s|$))/)

应该会提供您要查找的结果。