【发布时间】:2015-06-25 16:01:29
【问题描述】:
请帮我把两个句子分成一组单词和字符并分别显示。
我的输入字符串是这样的:
如果你不哭,我会给你糖果。那我给你 自制蛋糕。
我到目前为止所做的如下:
$(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>
我的方法是否正确?任何帮助表示赞赏:)
【问题讨论】:
-
仅供参考 jQuery 是一个用于修改 DOM 的库,在这种情况下它没有用处。
-
javascript 有拆分功能。在这种情况下,它不会得到你想要的东西,但这是一个好的开始。
var str = "your string"; str.split(" ");.. 看看这是否适合你 -
@depperm 我将发布我到目前为止所做的事情,我使用了 JavaScript 拆分方法和 reg-ex。 :)
标签: javascript arrays regex split