Reputation: 10140
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 []
)
Upvotes: 3
Views: 1907
Reputation: 89547
You can use this code and put in the capturing group all parts you want to skip:
var q = 'SELECT * FROM [Users] u aNd GeT sElEct * from [Users] U';
q = q.replace(/(\[[^\]]+\])|\w+/g, function(m, g1) {
return (g1) ? m : m.toLowerCase(); });
The method toLowerCase()
is applied to the whole match only if the capturing group is defined.
I used \w
to make the pattern shorter, but since it is useless to replace digits, lowercase letters and underscores, you can replace it with [A-Z]
pattern detail:
\[ # a literal [
[^\]]+ # character class with all characters except ] (repeated one or more times)
\] # a literal ]
Note that you don't need to escape the closing square bracket (or only for very old versions of internet explorer):), you can write: \[[^]]+]
Upvotes: 1
Reputation: 39355
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.
q = q.replace(/(?:\s|^)(\w+)(?=\s|$)/g, function(match)
Upvotes: 3