开发者

Retrieving part of a string using jQuery / JavaScript

开发者 https://www.devze.com 2022-12-24 07:48 出处:网络
I know how I would achieve this using PHP, but with jQuery / JavaScript I\'m not sure how t开发者_StackOverflow社区o, here\'s the string I\'m dealing with (It\'s the name attribute from a input elemen

I know how I would achieve this using PHP, but with jQuery / JavaScript I'm not sure how t开发者_StackOverflow社区o, 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.


You can use a regex, like this:

var part = /\]\[(.+?)\]$/.exec('Field[0][some_random_text]')[1]


I'm personally a fan of split():

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


door number 4:

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


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消