-1

Now that I have an array of elements. I want to turn them into array of strings and parse out the information after onclick. So i guess I have two questions, first is how to turn them into strings second is how to use regex to parse them? I can write the regex myself but I want to know how to apply it to the string in javascript.

First I did this:

var array = $('a[onclick*="findCustomer"]');

Now, I have a list of this:

    <a href="javascript:void(0);" onclick="findCustomer('James Smith',808-371-   4984,"Hawaii")">James Smith</a>

So my question is how to turn it into an array of string and how to parse out the Customer's name, phone number and state from that.

TitanTheYaphet
  • 113
  • 1
  • 4
  • 15
  • Parse what information? Are these elements form fields, and you want the values? Divs with element data? Need more details, sample HTML would be helpful. – Chris Baker Jan 23 '13 at 03:05
  • 1
    Please read [**this**](http://stackoverflow.com/a/1732454/1615483) about why you **should not** try to parse x/html with regex – Paul S. Jan 23 '13 at 03:27
  • `808-371- 4984` is not surounded with quotes and `Hawaii` is but with double quotes which are already around, so backslash them or put simple quotes. – Bali Balo Jan 23 '13 at 03:31
  • @BaliBalo a backslash is not an escape character in HTML (as it is in JavaScript). You would have to encode the `"`s to `"` or `"` and encode `'` as `'` (for safety). – Paul S. Jan 23 '13 at 03:39
  • Yeah you're right, my bad. – Bali Balo Jan 23 '13 at 03:44

1 Answers1

0

So my question is how to turn it into an array of string and how to parse out the Customer's name, phone number and state from that.

First get all the onclick attributes (as you seem to want to use jQuery, this can be done using $.map)

var array = $.map($('a[onclick*="findCustomer"]'), function (elm) {
    return elm.getAttribute('onclick');
}); // `array` is now an array of the _onclick_ attributes

Then parse the attribute, for example with $.each

$.each(array, function (key, val) {
    var parts = val.slice(val.indexOf('(')+1, val.lastIndexOf(')')).split(',');
    // parts[0] is name, parts[1] is number, parts[2] is state
    // you'll need to trim quotes
});

It is a really bad idea to try to parse x/HTML with RegExp as explained here. The method I've shown should be okay as you know the structure of the onclick attribute. A much better solution, however, would be to have this data accessible via some other method which does not involve parsing HTML at all.

Community
  • 1
  • 1
Paul S.
  • 64,864
  • 9
  • 122
  • 138