Jump to content

Replace() And Regular Expressions


lanmind

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");

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...