0

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.

4 Answers 4

3

You can use a regex, like this:

var part = /\]\[(.+?)\]$/.exec('Field[0][some_random_text]')[1]
Sign up to request clarification or add additional context in comments.

Comments

1

I'm personally a fan of split():

// name being the variable that is holding the string.
name.split('[')[2].replace(']','');

Comments

1

door number 4:

var s = "Field[0][some_random_text]";
var x = s.substring(s.lastIndexOf("[")+1, s.length - 1);
alert(x);

2 Comments

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
did a simple test, a loop of 100.000 iterations, substring method took 38ms, regex 396ms gloat :)
0

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/

2 Comments

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

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.