简体   繁体   English

使用jQuery / JavaScript检索字符串的一部分

[英]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): 我知道如何使用PHP实现此目的,但是我不确定如何使用jQuery / JavaScript,这是我正在处理的字符串(这是输入元素的name属性):

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. 我想检索值some_random_text并将其some_random_text变量,我想我通常会使用regex来完成此任务,但不确定如何在JavaScript中完成。 Here are some characteristics of this name attribute. 这是此名称属性的一些特征。

  • It will always be in this format string[string][string] 它将始终采用这种格式string[string][string]
  • Each of the strings can be any length 每个字符串可以是任意长度

How would I get the some_random_text string? 我将如何获取some_random_text字符串?

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(): 我个人是split()的粉丝:

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

door number 4: 4号门:

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

assuming Jquery. 假设使用Jquery。 If I understand, you are trying to get the name attribute. 据我了解,您正在尝试获取name属性。

var name = $("img").attr("name")); 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/ “ img”可以是选择元素的多种方式中的任何一种,更多信息请参见http://api.jquery.com/attr/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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