1

We use a regex to test for 'illegal' characters when a user provides a 'Version Name' before we save their content. The accepted characters are: A-Z, 0-9 and blank space. We test this using the following:

var version_name = document.getElementById('txtSaveVersionName').value;
if(version_name.search(/[^A-Za-z0-9\s]/)!= -1){ 
  alert("Warning illegal characters have been removed etc");
  version_name.replace(/[^A-Za-z0-9\s]/g,'');
  document.getElementById('txtSaveVersionName').value = version_name;
}

This works fine when a user keys their version name. However the version name can also be populated from data taken from a dynamically populated select box - version names loaded in from our system.

When this occurs, the regexp throws out the space in the name. So "My Version" becomes "MyVersion"? This does not occur when the user types "My Version".

So it appears that the value taken from the select box contains a character that looks like a space but is not. I have copied this value from the text box into a unicode converter (http://rishida.net/tools/conversion/) that identifies the characters underlying values and both sets are reported as 0020 (space), yet only ones throws an exception??

Is there a way to identify what the character is that is causing this issue?

Any thoughts greatly appreciated!

Cheers

Mark

1
  • wait, does it throw an exception, or does it return the wrong string, or both? Apr 17, 2013 at 10:22

2 Answers 2

2

Try:

var str= getSelectBoxValue();
var rez = ""; 
for (var i=0;i<str.length;i++) 
    rez = rez+str[i]+"["+str.charCodeAt(i)+"]"; 

alert(rez);

It should give you the unicode values of all the characters in the string the way Javascript sees them. When you copy it from the screen, it could be the browser/OS that converts some weird UTF character into regular "0x20" character for some reason.

1
  • Great! Using charCodeAt I found that the space keyed by our users was charCode 32 "space", whereas the space being loaded into our select box was charCode 160 "non-breaking space". This wasn't being trapped by the \s in my regex. Adding an additional \00A0 has caught it. Many thanks!
    – Needaf1x
    Apr 17, 2013 at 13:32
2

I noticed you have a bug in your code:

version_name.replace(/[^A-Za-z0-9\s]/g,'');

Should be

version_name = version_name.replace(/[^A-Za-z0-9\s]/g,'');

As, of course, replace creates a new string, it doesn't modify the existing string.

As you are finding that the replace sometimes works and sometimes doesn't I would suspect that you have implimented this correctly in one place and incorrectly in another.

1
  • Thanks, the snippet wasn't actually a copy and paste and we are setting the value appropiatelty in the real code.
    – Needaf1x
    Apr 17, 2013 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.