Liam Fell
Liam Fell

Reputation: 1320

Checking for a pattern using regex in jQuery

I'm attempting to use reg ex in jQuery to test whether or not a variable contains a specific pattern, if it does I'm attempting to trim the string. Here's is some pseudo code that details what I need.

     var $test = 12345_4
     if ($test contains '_[0-100]'){
       remove '_' && [0-100]
       // $test would equal 12345
     }
     else {
      //do something
    }

Is it possible to achieve something like this using jQuery? Thanks

Upvotes: 1

Views: 91

Answers (3)

Manam
Manam

Reputation: 355

You can do it 2 ways, using javascript match or replace: here are the examples:

var str = "Visit Microsoft!";
var res = str.replace("Microsoft", "W3Schools");

Result: Visit W3Schools!

var str = "The rain in SPAIN stays mainly in the plain"; 
var res = str.match(/ain/g);

Result: ain,ain,ain

Sources: http://www.w3schools.com/jsref/jsref_replace.asp http://www.w3schools.com/jsref/jsref_match.asp

here are some regular expression cheat sheets, you can use as @marcho have mentioned: http://www.javascriptkit.com/javatutors/redev2.shtml

Upvotes: 0

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

Yeah, as simple as this:

/[0-9]+(\_[0-9])/

Test it:

https://regex101.com/r/eT9nS3/1

Upvotes: 0

anubhava
anubhava

Reputation: 784998

You can use .replace:

var $test = '12345_4'
$test = $test.replace(/_(\d{1,2}|100)\b/g, '')

console.log($test)
// 12345

  • _(\d{1,2}|100) will match underscore followed by any number between 0 and 100
  • If match fails your input remains unchanged

Upvotes: 1

Related Questions