Jump to content

Replace() And Regular Expressions


lanmind
 Share

Recommended Posts

Hello everybody,I'm currently using the replace method and regexs twice to replace space characters (\040) at the beginning and end of a string with nothing like so:

var string = " good day ";// replace spaces at the beginning (^) string = string.replace(/^\040*/,"");// replace spaces at the end ($)string = string.replace(/\040*$/,"");

I haven't been able to figure out why I can't replace the spaces at the beginning and the end of the string in one statement like so:

var string = " good day ";// replace spaces at the beginning and end (^,$)string = string.replace(/^\040*$/,"");

I don't want to replace the space character between the two words "good" and "day" so the global "g" modifier won't work in this case. Thank you for any help if you love a regex!

Link to comment
Share on other sites

/^\040*$/ will only match a string with nothing but spaces in it. If you want to do a double-trim, you can do:

string = string.replace(/^\s*(.*?)\s*$/,"$1");

Edited by Synook
Link to comment
Share on other sites

/^\040*$/ will only match a string with nothing but spaces in it. If you want to do a double-trim, you can do:
string = string.replace(/^\s*(.*?)\s*$/,"$1");

After a while I figured out that "$1" was a backreference. I hadn't used a backreference before. Works fine Thank you.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...