2

I add a string (i.e. 'Bob Smith') from a jQuery click event trapped using the on function . . .

$(".vendorLookup").on("click", { fullName: $(this).text() }, displayAddy);

In the displayAddy handler for the click event, I extract the string (a persons first and last name) and split out the first and last name . . .

var name = event.data.fullName;
var parts = name.split(" ");

IE can figure this one out but Chrome and Firefox will not split unless I use the regular expression split(/\s/) (unless I use the w3schools.com Tryit code editor and then it works).

Question: what exactly is going on here and when will I get bit by this later on when parsing for spaces cross-browser?

(Note: I don't think it matters but I am running this script on a wiki page in SharePoint 2010)

5
  • Split does work with a string. name.split(" "); is valid. Commented Jan 17, 2012 at 19:58
  • Since this bare bones example works in Firefox, Chrome, and IE, there must be something else going on since split() has no issues splitting on the space. Have you tried to log event.data.fullName to the browser? Commented Jan 17, 2012 at 19:59
  • Can you provide one runnable sample? jsfiddle.net Commented Jan 17, 2012 at 20:00
  • 2
    \s matches all whitespace, so my guess is that you have a different whitespace character in your string than you think you do. Commented Jan 17, 2012 at 20:07
  • Good call, David! The SharePoint web editor converted the space to  . Sure enough, checking for a string literal space entered with the space bar doesn't match. If you want to submit an answer to that effect I'll mark it for you. I would still like to know why Chrome and FF can't figure it out whilst IE can. Commented Jan 18, 2012 at 18:26

1 Answer 1

1

I'm not sure whats going on (I tested it and see some weird behavior), but you can work around it by doing something like this

function displayAddy() {

    var parts = $(this).text().split(" ");

    $('#fname').html(parts[0]);
    $('#lname').html(parts[1]);
}

$('#name').on("click", displayAddy);

Since the event is being passed off to a callback the callback already has a this object. in this instance the this object is going to be DOM object with the class #name.

Here's an example of it in action.

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

1 Comment

Thanks, Brombomb but the problem is in the html and the way browsers interpret the space character (see my comment in the original post and David's above). I already had a workaround which was to use the reg expression \s instead of a literal space.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.