1

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

4
  • jQuery is helpful for things related to the DOM. Do not seek jQuery solutions for other things as it's irrelevant. Commented Jun 13, 2016 at 13:29
  • @plalx jQuery has useful things outside of DOM as well. AJAX, iterators etc Commented Jun 13, 2016 at 13:51
  • @alex Why would you use jQuery to iterate over an non-dom nodes array? Use native array functions. As for AJAX it was true for a while, but now that fetch/Request/Promise are getting supported it will become obsolete. Commented Jun 13, 2016 at 14:00
  • @plalx In 2009 it was a great idea. You're right it is less useful as browsers are filling in those gaps. Commented Jun 13, 2016 at 14:02

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

Yeah, as simple as this:

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

Test it:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.