简体   繁体   English

如何在javascript中操纵字符串?

[英]How to manipulate a string in javascript?

I'm new to javascript and need some help! 我是javascript新手,需要一些帮助! I want to make a magic 8-ball script that pulls a specific answer for certain questions. 我想制作一个魔术的8球脚本,为某些问题提供特定的答案。 So far I have it so that if I ask a specific question, it will give me one answer, but I want to alter it so that it will give me a specific answer based on whether or not the question uses 'who' or 'what' or if a question uses an 'a' 'd' and 'b' and things like that. 到目前为止,我有一个问题,如果我问一个特定的问题,它将给我一个答案,但是我想对其进行更改,以便根据问题是使用“谁”还是“什么”来给我一个特定的答案。 ”或问题是否使用“ a”,“ d”和“ b”之类的东西。 Does anyone know how to do this and could you possibly help me? 有谁知道该怎么做,你能帮我吗? I'm completely stuck and don't know how to go about this. 我完全被困住了,不知道该怎么做。 Thank you for your help! 谢谢您的帮助!

    <script>


        function eightBall() {
            var answer = document.getElementById("answerBox").value;
            var images = ['answerYes.png', 'answerNo.png', 'answerAskLater.png', 'answerNotL.png', 'answerMaybe.png'];

            if (answer.search(/Will I be rich?/) > -1) {
                var askLater = '../images/answerAskLater.png'
                document.getElementById('eightTemplate').src = askLater;

            } else if (answer.search(/Will I be happy?/) > -1) {
                var no = '../images/answerNo.png'
                document.getElementById('eightTemplate').src = no;
            } else if (answer.search(/Will I live to be 90 years old?/) > -1) {
                var yes = '../images/answerYes.png'
                document.getElementById('eightTemplate').src = yes;
            } else if (answer.search(/Will I be married later in life?/) > -1) {
                var notLikely = '../images/answerNotL.png'
                document.getElementById('eightTemplate').src = notLikely;
            } else if (answer.search(/Can I have a puppy?/) > -1) {
                var maybe = '../images/answerMaybe.png'
                document.getElementById('eightTemplate').src = maybe;
            }

        }


    </script>

If you want to see if a question contains a certain word, then I would suggest using javascript's Regular Expressions . 如果您想查看问题中是否包含某个单词,那么建议您使用javascript的正则表达式 these expressions can be used to test or extract certain words or even sentence structures. 这些表达式可用于测试或提取某些单词甚至句子结构。 For instance: 例如:

var questionPattern = new RegExp('.+\?$');

//returns true if answer ends with question mark
var isQuestion = questionPattern.test(answer); 

You're actually already using regular expressions without even knowing it. 实际上,您实际上已经在使用正则表达式,甚至都不知道。 Everything you passed to the search function is a regular expression in short hand. 您传递给搜索功能的所有内容都是简写形式的正则表达式。 Example: 例:

/.+\?$/

is the shorthand way of declared the same regular expression i did in the above code. 是在上面的代码中声明相同正则表达式的简写方式。 You can also construct regular expressions to see if a string begins with the word what: 您还可以构造正则表达式以查看字符串是否以单词what开头:

/^(what)/i

For more information on regular expressions, check here . 有关正则表达式的更多信息,请参见此处 Hope it helps! 希望能帮助到你!

Instead of lots of similar if/then/else statements, I suggest putting all the cases in a table, so you can loop over it. 建议不要将所有案例放在一个表中,而不是使用许多类似的if/then/else语句,这样您就可以遍历它。

function eightBall() {
    var possibilities = [
        { match: /Will I be rich\?/,
          answer: 'AskLater' },
        { match: /Will I be happy\?/,
          answer: 'No' },
        ...
    ];
    var answer = document.getElementById('answerBox').value;
    for (var i = 0; i < possibilities.length; i++) {
        if (possibilities[i].test(answer)) {
            document.getElementById('eightTemplate').src = '../images/answer' + possibilities[i].answer + '.png';
            return;
        }
    }
    // Display a default answer here
}

You can add regular expressions matching who , what , letters, or anything else to the possibilities table. 您可以将匹配whowhat ,letter或其他任何内容的正则表达式添加到possibilities表。

There is also a simpler way to achieve this: str.toLowerCase().contains("who"); 还有一种更简单的方法可以实现这一点: str.toLowerCase().contains("who"); but RegExp is your choice for complicated checks. 但是RegExp是您进行复杂检查的选择。

The thing between the slashes doesn't have to match the entire string. 斜线之间的东西不必匹配整个字符串。 The following will show answerYes.png if the string contains a lowercase 'b' anywhere. 如果字符串在任何地方都包含小写字母“ b”,则以下内容将显示answerYes.png For example, it will match when the string is "Do you like blueberries?" 例如,当字符串为“您喜欢蓝莓吗?”时,它将匹配。 or "abcd". 或“ abcd”。

else if (answer.search(/b/) > -1) {
    var yes = '../images/answerYes.png'
    document.getElementById('eightTemplate').src = yes;
}

For clarity, it's probably a good idea to rename your answer variable to question , since it looks like you're using it to hold the value of the question. 为了清楚起见,将您的answer变量重命名为question可能是一个好主意,因为您似乎正在使用它来保存问题的值。

This approach will probably be fine for what you're doing. 这种方法可能适合您的工作。 It will work as long as all you want to do is simply find a word, letter, or phrase in the question. 只要您只想在问题中找到单词,字母或短语,它就会起作用。 If you want to get more sophisticated, and match a general pattern instead of a specific string of text, you may want to learn about regular expressions (RegExp) as others have suggested. 如果您想变得更复杂,并且匹配常规模式而不是特定的文本字符串,则可能要学习其他人建议的正则表达式(RegExp)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM