lanmind 0 Posted September 7, 2009 Report 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! Quote Link to post Share on other sites
Synook 47 Posted September 7, 2009 Report Share Posted September 7, 2009 (edited) /^\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 September 7, 2009 by Synook Quote Link to post Share on other sites
dsonesuk 921 Posted September 7, 2009 Report Share Posted September 7, 2009 (edited) this seems to workstring = string.replace(/^[\040]|[\040]$/g,"");orstring = string.replace(/^[\s]|[\s]$/g,"") Edited September 7, 2009 by dsonesuk Quote Link to post Share on other sites
lanmind 0 Posted September 7, 2009 Author Report 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. Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.