Jump to content

Regex - Only want to use certain part ??


JChilds

Recommended Posts

I'm using the code:

 

javascript:
var report = document.body.innerHTML;
var ID = report.match (/id_\d{1,9}/g);
alert(ID,"");

 

To extract everything matching id_XXXXXXX where x is anywhere from 1 to 9 numbers.

 

It returns an array perfectly. But it returns it like "id_1234567, id_6472826, id_7998326"

And i want it to return it like "1234567, 6472826, 7998326"

 

Is there an easy way to go about doing this?

Link to comment
Share on other sites

Hmmm, I would think you could achieve that with a modified RegEx, but I couldn't figure it out. Here's a quick fix:

 

function getIDs (string) {

  var IDs = string.match (/id_\d{1,9}/g);
  for (var i=0; i<IDs.length; i++) {
    IDs[i] = IDs[i].substr(3);
  }
  return IDs;
}

var ID = getIDs (document.body.innerHTML);

Link to comment
Share on other sites

Thanks for that  ;D

 

I've been playing with regex's for the last few hours and can't figure it out  :'(

 

I'll leave this thread 'open' for a little longer and see if anyone else can get it to work.

 

All of this code is going on one line (I only have access to one button - nothing else)

And in total, its already half an A4 page of code. So don't want to make it worse for myself.

Link to comment
Share on other sites

Using a reg ex:

  I used:  /([0-9]+)$/    -- to me means: Ends with any amount of numbers 0-9.

<script type="text/javascript">
var myA = new Array("id_12345","id_142442","id_124125");
  var x = myA.length;

for(i=0;i<x;i++)
{
  var str = myA[i].match(/([0-9]+)$/);
  if(str) {
    myA[i] = str[0];
  }
}

for(a=0;a<myA.length;a++)
{
  document.write(myA[a] + '<br />');
}//returns just the numbers
</script>

 

 

If the array always holds values of id_#####  where the "id_" is guaranteed to be there and then followed by a random amount of letters, you could just use a substr method like posted above.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.