Wednesday 6 October 2010

Removing spaces from a string in Javascript

Another reminder post for myself really.

If you have a Javascript value that contains spaces or other characters, but want to use the value as an element name or variable name, then you need to remove the bad characters from the string.
This will do it.

"my var with spaces & wierd chars*".replace(/[^\w]/g,"_");

this will output "my_var_with_spaces___wierd_chars_".

No comments:

Post a Comment