简体   繁体   English

Javascript获取属性值

[英]Javascript get value in attribute

I am using jquery .attr in an input type so when I run this 我在输入类型中使用jquery .attr ,所以当我运行它时

console.log('name: '+$(this).attr('name'));

output is: name: user_project_category[65][skill][9] 输出为: name: user_project_category[65][skill][9]

How can I get the 65 and 9? 我如何获得65和9?

You can use Regular Expressions to extract text from between the brackets into an array and then you can access the array to get the values you want, you can either extract all text between brackets or just the numbers: 您可以使用正则表达式将括号之间的文本提取到数组中,然后可以访问该数组以获取所需的值,可以提取括号之间的所有文本或仅提取数字:

 var yourInput = "user_project_category[65][skill][9]"; var allMatches = yourInput.match(/\\[(.*?)\\]/g); console.log(allMatches[0]); console.log(allMatches[2]); var numberMatches = yourInput.match(/\\[([0-9]*?)\\]/g); console.log(numberMatches[0]); console.log(numberMatches[1]); 

Use regular expression or split function in JavaScript 在JavaScript中使用正则表达式或拆分函数

var output= 'user_project_category[65][skill][9]';
output.split(/(\d+)/)[1];
output.split(/(\d+)/)[3];

 var data = "name: user_project_category[65][skill][9]"; console.log(data.split("[")[1].slice(0,-1))//use split to get 65] use slice to remove ] console.log(data.split("[")[3].slice(0,-1))//use split to get 9] use slice to remove ] 

  1. You can use split with slice 您可以使用切片分割

Assuming this is not dynamic and format is the same. 假设这不是动态的,并且格式相同。 for dynamic use regex 用于动态使用正则表达式

Use regex. 使用正则表达式。

var output = 'user_project_category[65][skill][9]';
var numbers = output.match(/\d+/g).map(Number);
alert(numbers);

output: 65,9 输出: 65,9

Do whatever you want to do with number. 用数字做任何你想做的事。

working fiddle 工作小提琴

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

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