Asked  7 Months ago    Answers:  5   Viewed   49 times

I have a string in JavaScript (e.g #box2) and I just want the 2 from it.

I tried:

var thestring = $(this).attr('href');
var thenum = thestring.replace( /(^.+)(wd+w)(.+$)/i,'$2');

It still returns #box2 in the alert, how can I get it to work?

It needs to accommodate for any length number attached on the end.



For this specific example,

 var thenum = thestring.replace( /^D+/g, ''); // replace all leading non-digits with nothing

in the general case:

 thenum = "foo3bar5".match(/d+/)[0] // "3"

Since this answer gained popularity for some reason, here's a bonus: regex generator.

function getre(str, num) {
  if(str === num) return 'nice try';
  var res = [/^D+/g,/D+$/g,/^D+|D+$/g,/D+/g,/D.*/g, /.*D/g,/^D+|D.*$/g,/.*D(?=d)|D+$/g];
  for(var i = 0; i < res.length; i++)
    if(str.replace(res[i], '') === num) 
      return 'num = str.replace(/' + res[i].source + '/g, "")';
  return 'no idea';
function update() {
  $ = function(x) { return document.getElementById(x) };
  var re = getre($('str').value, $('num').value);
  $('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>
Tuesday, June 1, 2021
answered 7 Months ago

If you only need the dictionary keys 1, 2, and 3 use: your_dict.keys().

If you only need the dictionary values -0.3246, -0.9185, and -3985 use: your_dict.values().

If you want both keys and values use: your_dict.items() which returns a list of tuples [(key1, value1), (key2, value2), ...].

Saturday, June 12, 2021
answered 6 Months ago

You should use matcher.find() instead.

Friday, August 6, 2021
answered 4 Months ago

In your 2nd regex, you need to remove that ? from the first part, and make it [1-5] instead of [0-5]:


And if you want to be flexible enough to allow both 7 and 07, then use [0-5]:


And then, simplifying the above regex, you can use:

[0-5]?[0-9]   // ? makes [0-5] part optional
Wednesday, August 25, 2021
Ryan Stewart
answered 4 Months ago

Use following regex, you're using wrong bracket

Regex Demo and Explanation


You can also use

Regex Demo and Explanation

Friday, September 3, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :