views:

65

answers:

4

I know how I would achieve this using PHP, but with jQuery / JavaScript I'm not sure how to, here's the string I'm dealing with (It's the name attribute from a input element):

Field[0][some_random_text]

I want to retrieve the value some_random_text and slap it in a variable, I guess I would usually use regex to accomplish this task but not sure how this is done in JavaScript. Here are some characteristics of this name attribute.

  • It will always be in this format string[string][string]
  • Each of the strings can be any length

How would I get the some_random_text string?

I'd like to stick to the standard set of functions if possible.

+3  A: 

You can use a regex, like this:

var part = /\]\[(.+?)\]$/.exec('Field[0][some_random_text]')[1]
SLaks
+1 Perfect! Cheers!
ILMV
A: 

assuming Jquery. If I understand, you are trying to get the name attribute.

var name = $("img").attr("name"));

"img" can be any of a number of ways of selecting an element, more at http://api.jquery.com/attr/

Russell Steen
He's asking how to to parse an arbitrary string.
SLaks
Hi there, I actually wanted to get a portion of the attribute value, SLaks answer achieved this very well. Thanks :)
ILMV
+1  A: 

I'm personally a fan of split():

// name being the variable that is holding the string.
name.split('[')[2].replace(']','');
Chibu
Unfortunately neither am I, but many thanks for trying! :)
ILMV
+1  A: 

door number 4:

var s = "Field[0][some_random_text]";
var x = s.substring(s.lastIndexOf("[")+1, s.length - 1);
alert(x);
Les
Thanks for your answer too! This did in fact work, would be interesting (when I learn how :D) to compare the performance of your an SLaks answer. Many thanks! +1
ILMV
did a simple test, a loop of 100.000 iterations, substring method took 38ms, regex 396ms *gloat* :)
Les