lanmind Posted September 7, 2009 Share Posted September 7, 2009 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 More sharing options...
Synook Posted September 7, 2009 Share Posted September 7, 2009 /^\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 More sharing options...
dsonesuk Posted September 7, 2009 Share Posted September 7, 2009 this seems to workstring = string.replace(/^[\040]|[\040]$/g,"");orstring = string.replace(/^[\s]|[\s]$/g,"") Link to comment Share on other sites More sharing options...
lanmind Posted September 7, 2009 Author Share Posted September 7, 2009 /^\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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.