Good day experts. I am new to programming, and have encountered a problem that I don’t know how to solve yet, and I hope for your help.
Several types of text can get into the strik variable:
1. (any number) losses in a row (need to get losses )
2. (any number) loss (need to get loss )
3. (any number) wins in a row (you need to get wins )
4. (any number) win (need to get win )
For example, got the first option:
var strik = "7 losses in a row";
In the result variable to put the word. But the word depends on which version of the text fell into the variable strik. In our case, losses. Ie, to get from 7 losses in a row only losses and put in the result. It should be like this:
var result = " losses ";
Accordingly, get into a var strik with something like 4 win, the word win should fall into the result variable.
I have a solution to the problem, but I am sure that it is wildly nubsky, and I don’t know something. (I haven’t figured out regular expressions yet).
So I want to know which solution will be the most correct in this problem.

  • I have a solution to the problem - it is worth adding it - Grundy

4 answers 4

You can try this.

var text = "7 losses in a row"; var spl = text.split(" "); var result = spl[1]; console.log(result); 
  • Thanks for such a quick reply. In my opinion, this is the most correct decision, although I have been busy with this for half a day already =) - Black_Dog
  • You are welcome! :)) - Amandi

If you also need to check for the correctness of the input data, or if you are just a perfectionist :), you can do so

 function getResult(strik) { if (/^\d+ losses in a row$/.test(strik)) return 'losses'; if (/^\d+ loss$/.test(strik)) return 'loss'; if (/^\d+ wins in a row$/.test(strik)) return 'wins'; if (/^\d+ win$/.test(strik)) return 'win'; return null; } console.log(getResult("7 losses in a row")); //losses console.log(getResult("4 loses in a row")); //null 

those. we check all variants with regular expressions. I would do that :).

    You can use regular expressions to solve this problem, for example, this option:

     var results = str.match( /\d+\s+(\w+)/i ); 

    results[1] will contain the necessary data

      I would make an array of words that need to be searched, and take a loop to cycle through the array, and look for a match through match .

      • The offer is good, but it seems to me not the most correct, although it works, thanks for the quick reply!) - Black_Dog