Jump to content

[SOLVED] Get id of an input from a string using a regular expression


Axeia

Recommended Posts

Using the mozilla javascript reference as my guideline I thought this would work, but it doesn't.  (s is the string)

var regex = /<input.*id='([^'])[^>]*/;
var arr = regex.exec( s );
if( arr != null)
alert( arr[1] );

 

String is like this:

<input value='whateverrrrrrrrr' id='g29' name='download[]' type='checkbox'/>

I'd love to hear any optimisations I could make as well as this thing is gonna be used on several hundred strings. (and in that light it might be useful to know that the id will always be g followed by numbers).

Link to comment
Share on other sites

Can't do either as it's for adding a custom parser to jquery's tablesorter plugin.

it will only be input fields, but the plugin converts the contents of the tablecell to a string.

 

So not much choice but to use a regular expression, or come to think of it.. creating a new node using .innerHTML, but I think that would be slower.

Anyhow Ken2k7's code works, any idea as to what's wrong with my regular expression? Did I use some feature not supported by javascripts implementation of regular expressions?

 

And for the the curious, the total sorter code has become:

	$.tablesorter.addParser({
    id: 'input',
    is: function(s) {
        return false;
    },
    format: function(s) {
    	var regex = /id=[\'\"]{0,1}(\w+)/;
    	var arr = regex.exec(s);
    		return document.getElementById( arr[1] ).checked;
    },
    type: "numeric"
});

Link to comment
Share on other sites

Yes, there is an issue with your Regex, but not with anything particularly wrong. I just though mine is shorter.

 

var regex = /<input.*id='([^'])[^>]*/;

See where you have ([^'])? Well, using that set, you're matching only once. You need a + or a * to match more than once. So it should be ([^']*). ;)

 

You need the * rather than + in case the id field is empty.

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.