awaken
awaken

Reputation: 809

protractor: comparing strings with greater than Jasmine matcher

I'm trying to compare between:

string1 = 'client 90 llc'

string2 = 'client 501 llc'

using:

expect(client[i]).toBeGreaterThan(client[i-1]);

FAILS because the compare function thinks 90 is greater than 501, i'm assuming because its doing character by character comparision. Is there a way to make it where it compares the whole number? Because the web application list string2 after string1 because 501 is bigger than 90.

UPDATE: there is no particular format for these strings. It can be

'client abc'
'client 90 llc'
'client 501 llc'
'abcclient'
'client111'
'client 22'
'33client'

Upvotes: 1

Views: 1084

Answers (2)

giri-sh
giri-sh

Reputation: 6962

Yes, Jasmine does a character based comparison. One way to do this is to split the string into parts and then compare the numbers only as shown below -

string1 = 'client 90 llc';
string2 = 'client 501 llc';
var newString1 = parseInt(string1.substring(string1.indexOf(' '), string1.lastIndexOf(' ')));
var newString2 = parseInt(string2.substring(string2.indexOf(' '), string2.lastIndexOf(' ')));
expect(newString2).toBeGreaterThan(newString1); //501 > 90 - should return true

I am assuming that your string pattern will be the same as you have mentioned above in the snippet. Or you can use regular expressions in place of substring() function and get the result. Hope this helps.

Upvotes: 1

Michael Radionov
Michael Radionov

Reputation: 13309

If you know the format of the string, you can extract values with the help of Regular Expressions. In you case you want to extract a varying number in the middle of the string, which has common parts. The following regular expression might work:

/^client (\d+) llc$/
  • ^ - beginning of the string
  • () - capture specific group of characters
  • \d - represents a digit (0-9), backslash is required because it is a character sequence, not to match a letter d
  • + - character may appear 1 or more times
  • $ - end of the string

As a result, we'll be able to find a group of digits in the middle of the string. You can create an utility function to extract the value:

function extractNumber(string) {
    var pattern = /^client (\d+) llc$/;
    var match = string.match(pattern);
    if (match !== null) {
        // return the value of a group (\d+) and convert it to number
        return Number(match[1]); 
        // match[0] - holds a match of entire pattern
    }
    return null; // unable to extract a number
}

And use it in tests:

var number1 = extractNumber(string1); // 90
var number2 = extractNumber(string2); // 501
expect(number1).toBeGreaterThan(number2);

Upvotes: 2

Related Questions