Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...