1

I want to check if a string ends with

- v{number}

So for example

hello world           false
hello world - v2      true
hello world - v       false
hello world - v88     true

Not entirely sure how to go about doing this RegEx.

var str = 'hello world - v1';
var patt = new RegExp("/^ - v\d*$/");
var res = patt.test(str);
console.log(res);

How could I fix the above RegEx?

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
ditto
  • 5,917
  • 10
  • 51
  • 88

2 Answers2

5

Just use this without checking anything else in the beginning

- v\d+$

This way you make sure it ends with - v followed by at least one digit. See it live in https://regex101.com/r/pB6vP5/1

Then, your expression needs to be:

var patt = new RegExp("- v\\d+$");

As stated by anubhava in another answer:

  • No need for /
  • Requires double escaping for \d.

var str = 'hello world - v15';
var patt = new RegExp("- v\\d+$");
var res = patt.test(str);
console.log(res);
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
0

This is a solution that achieves the same results without a Regex. Worth giving it a try.

function stringEndsWithVersionNum(string) 
{
    var parts   = string.split('- v');
    if(parts[0] !== string) //if the string has '- v' in it
    {
        var number = parts[parts.length -1].trim();//get the string after -v
        return !isNaN(number) && number.length > 0;//if string is number, return true. Otherwise false.
    }
    return false; 
}

Please use like so:

stringEndsWithVersionNum('hello world - v32')//returns true
stringEndsWithVersionNum('hello world - v'); //returns false 
stringEndsWithVersionNum('hello world');     //returns false