0

I'm having an issue with matching a square bracket in a string with a regular expression in Javascript. I have tested the regex below, and it works for me:

"step_users[0]​[step]​[name]​".match(/step_users\[\d*\]/)

This regex matches the substring "step_users[0]", but what I really need to match is the substring "step_users[0][step]". I tried modifying the regex as follows, but it fails for me.

/step_users\[\d*\]\[step\]/

In fact, if i even add on the second '[', it fails. So, this also fails:

"step_users[0]​[step]​[name]​".match(/step_users\[\d*\]\[/)

Why would it match '[' for the first square bracket, but fail on the second?

1
  • Try give us a non-working jsFiddle. Commented Mar 20, 2012 at 7:47

1 Answer 1

2

You have a zero-width character in there!

"[0]​[".length === 5
"[0]​[".charCodeAt(3) === 8203

8203 is the word boundary character, a zero-width-space character. In fact, you have it between every pair of braces!

Remove it manually or dynamically as you fetch the data.

How I found it was simple. Your regex should have worked. So, I looked where it stopped working. An easy trick to find these zero-width spaces is to Shift-Arrow along the string.

Edit: A second after submitting, I thought of an easy way to remove it:

var destroyZWS = new RegExp(String.fromCharCode(8203), "g");
yourString.replace(destroyZWS, "");

This creates a regular expression, which globally searches for the specific ZWS character, and then replaces each occurrence with the empty string.

Sign up to request clarification or add additional context in comments.

3 Comments

Well...there we go then. Thanks. I suppose that's because I copied it out of the html name attribute output in my web inspector console.
@slave2zeros Enjoy. I just edited in a simple way to remove that bugger.
Well, normally they'll be coming from the name attribute of an HTML element, not copied from Safari's web inspector. It just happened to be a problem while testing in the console.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.