Jump to content

Replace() And Regular Expressions


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 post
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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...