[SOLVED] Replace all Caps to Small using JS RegExp

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

[SOLVED] Replace all Caps to Small using JS RegExp

Post by anjanesh »

Im trying to replace all capital letters to small letters in a string using JavaScript's RegExp.

Code: Select all

<script type=&quote;text/javascript&quote;>
content = &quote;This is A Sentence&quote;;
cExp = /&#1111;A-Z]/g;
sExp = /&#1111;a-z]/;
document.write(content+&quote;<br>&quote;);
content = content.replace(cExp,sExp);
document.write(content);
</script>
Instead all caps get replaced with the word null.
Any solutions ?

Thanks
Last edited by anjanesh on Thu Jun 16, 2005 8:22 am, edited 1 time in total.
Syranide
Forum Contributor
Posts: 281
Joined: Fri May 20, 2005 3:16 pm
Location: Sweden

Post by Syranide »

are you sure replace is regex? and are you sure of your regex?

otherwise, I believe strings have a function "toLower" "lowercase" or something like that that would do the trick much better.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Syranide wrote:are you sure replace is regex? and are you sure of your regex?

otherwise, I believe strings have a function "toLower" "lowercase" or something like that that would do the trick much better.
Yes replace() in JS does handle regex and yes there is a method tolower() or something like that for the job however ;)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

usage: string.toLowerCase()
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Thanks. Did not realize it was that easy.
Strange why the RegExp isnt working.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

anjanesh wrote:Strange why the RegExp isnt working.
The you've used replace() completely wrong, that's why that isn't working :)

Replace generally uses a regex pattern on the first parameter and then a string which includes the backreferences ($1, $2, $3 etc) for the second parameter. Here you've just put a regex in each of them.

JavaScript doesn't support the "e" modifier which is something you would need to do this too (but then you'd just be toLowerCase()'ing each uppercase letter so simply using toLowerCase() is much more sensible anyway) ;)
Post Reply