Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace an asterisk in Javascript using replace()?

Using JQuery, I'm extracting the value from what is essentially a query box for some data in a MySQL database. Knowing that most users will use an '*' (asterisk) as a wildcard value and that MySQL uses the '%' character, I want to convert any asterisks to '%'.

Normally, this would just be as simple as using

queryString = inputText.replace('*', '%');

but I've had little success with that. Javascript's replace() function only replaces the first occurrence, so it's not replacing the last asterisk in something like *Foo*

The second option I tried was using a regular expression, which also didn't work:

queryString = inputText.replace(/\x2a/g, '%');

How can I replace the '*' (asterisks) with a '%' (percent sign)? I'd imagine there's a really simple regular expression, or something I'm overlooking.

like image 283
S Pangborn Avatar asked Oct 02 '09 14:10

S Pangborn


3 Answers

Try:

queryString = inputText.replace(/\*/g, '%');
like image 96
Roatin Marth Avatar answered Oct 11 '22 06:10

Roatin Marth


Splitting a string into an array and then joining it back into a string is faster than regular expression replacements:

queryString = inputText.split("*").join("%");
like image 38
Ates Goral Avatar answered Oct 11 '22 06:10

Ates Goral


If you want to try passwords with a nice touch for remembering

str.replace(str.substr(1,str.length-3), str.substr(1,str.length-3).replace(/./g,"*"))

The output will be

1*********xY
like image 1
TorNadO Avatar answered Oct 11 '22 06:10

TorNadO