Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression: word between spaces

Sry for stupid question, but there is an example: http://jsfiddle.net/rb98M/

var q = 'SELECT CASE WHEN STATE IN ';
q = q.replace(/(^|\s)\w*(\s|$)/g, function(match) { return match.toLowerCase(); });
alert(q);

I have a string and i want to make lowerCase each word, that's between white spaces (and could be in start of line and end).

But, my result is:

select CASE when STATE in

and that's my problem. Why is it so?

Edit I expect to pass SELECT * FROM [Users] u and get select * from [Users] u and e.t.c (including each SQL statement and exclude any table names and properties in [])

like image 710
Maxim Zhukov Avatar asked Dec 12 '25 06:12

Maxim Zhukov


1 Answers

Since you are not separating the words with other punctuations. So I believe only using \S is sufficient for you.

q = q.replace(/(\S+)/g, function(match)

In your case it was not working because the \s\w*\s was eating the SELECT(with space at end) from the input and the CASE wasn't have enough space(\s) before it.

Here is how your input was matched using the regex:

SELECT CASE WHEN state IN 
^  m1 ^    ^ m2 ^     ^m3^

Its just ignored the CASE ad the state words from the regex. Because the space before the CASE was picked by the SELECT. You have mandatory space(\s) at the both sides of the word(i.e. \s\w*\s). In other words your regex has overlapping.

Updated regex:

q = q.replace(/(?:\s|^)(\w+)(?=\s|$)/g, function(match)
like image 101
Sabuj Hassan Avatar answered Dec 13 '25 21:12

Sabuj Hassan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!