views:

22

answers:

2

Is there a way to use a wildcard in a javascript bookmarklet?

For example, I have this:

javascript:(function(){var b=document.getElementsByName('send');for(var j=0;j<b.length;j++){if(b[j].value.match(/^Send Pattarapim a Thank you gift$/i)){b[j].click();break;}}})()

That worked great when the item was for "Pattarapim". But that "name" will change each time. Could I do anything to make that JS work regardless of what was in place of Pattarapim?

Thank You!

A: 

You can change the regex from

/^Send Pattarapim a Thank you gift$/i

to

/^Send .* a Thank you gift$/i

The . means "match any character here", and the * following it means "match zero or more of the preceding thing". So combined they mean, "match zero or more of any character here." (Or you might use + instead of *; + means "match one or more".) Note that that may be too broad, it depends on the text you'll be processing, but since you're starting with a ^, that tends to anchor it a bit and it'll probably be fine.

T.J. Crowder
I would just make that lazy instead of greedy, not that it is likely to make a difference in this case.
NullUserException
@NullUserException: Yeah, maybe, although since he's anchoring the beginning and end, let's just say it would be a very odd name indeed. :-) @Michael: To make it lazy, just put a `?` after the `*` or `+`.
T.J. Crowder
Working perfectly. Thank you!
Seatbelt99
A: 

If the user will know what name to match, then you can use the prompt() command to get the name from the user, and then build your regex dynamically:

javascript:(function(){var name=prompt("Name to find:","");var b=document.getElementsByName('send');for(var j=0;j<b.length;j++){if(b[j].value.match(new RegExp("^Send " + name + " a Thank you gift$","i"))){b[j].click();break;}}})()
JacobM