使用 Javascript 解析文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2024732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing text with Javascript
提问by Albert
I'm trying to use Javascript to parse text that has been entered in a text box - which would combine a variety of user-generated variables to create random activities. This might make more sense looking at the example. Some example input might be:
我正在尝试使用 Javascript 来解析在文本框中输入的文本 - 这将结合各种用户生成的变量来创建随机活动。看看这个例子,这可能更有意义。一些示例输入可能是:
Activity @Home @Out @Home Read @book for @time Clean up @room for @time @Out Eat at at @restaurant @book Enders Game Lord of the Rings @room bedroom garage basement @restaurant Red Robin McDonalds Starbucks @time 15 minutes 30 minutes 45 minutes 60 minutes
Pound/and signs would be used to separate different categories.
磅/和符号将用于分隔不同的类别。
The output would then be determined randomly from the given input, for example:
然后将根据给定的输入随机确定输出,例如:
"Eat at Starbucks." or "Read Lord of the Rings for 60 minutes." or "Clean garage for 30 minutes."
“去星巴克吃饭。” 或“阅读指环王 60 分钟。” 或“清洁车库 30 分钟”。
Is this doable? It seems like it should be fairly straightforward, but I do not know where to start. Any suggestions?
这是可行的吗?看起来应该相当简单,但我不知道从哪里开始。有什么建议?
Thanks,
谢谢,
Albert
阿尔伯特
采纳答案by David Pfeffer
No issue at all. Split the textbox value into an array based on line break characters. Then, go through the array one element at a time, sorting the values into variables for each section. Finally, use JavaScript's random number generator to randomly determine which of each group to select. Output to the user by assigning the value to an HTML element.
完全没有问题。根据换行符将文本框值拆分为数组。然后,一次遍历数组一个元素,将值排序到每个部分的变量中。最后,使用 JavaScript 的随机数生成器来随机确定要选择每个组中的哪一组。通过将值分配给 HTML 元素来输出给用户。
回答by Mene
How about:
怎么样:
var myText = ...; // Input text
var lines = myText.split("\n");
var numLines = lines.length;
var i;
var currentSection;
var sections = Array();
var phrases = Array();
// parse phrases
for (i = 0; i < numLines; i++) {
var line = lines[i];
if (line.indexOf('@') == 1) {
// start of e.g. time section, handled in nex loop
break;
} else {
// phrase
phrase.push(line);
}
}
// parse sections
for ( ; i < numLines; i++) {
var line = lines[i];
if (line.indexOf('@') == 1) {
// start of next section, handled in nex loop
currentSection = line;
sections[currentSection] = new Array();
} else {
// add section entry
sections[currentSection].push(line);
}
}
It's not too sophisticated, but does the job. Didn't test it though, but something like this should work. And where is the fun if this'd just work ;D
它不是太复杂,但可以完成工作。虽然没有测试它,但像这样的东西应该可以工作。如果这行得通,乐趣在哪里;D

