简体   繁体   中英

Retrieving part of a string using jQuery / JavaScript

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.

您可以使用正则表达式,如下所示:

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM