I have a string like following
value[0]
0
value
var matches = this.key.match('/[([0-9]+)]/'); // 1
if (null != matches) {
var num = matches[1]; // 2
}
How can the third point be accomplished?
You need to remove wrapping quotes, and escape the brackets.
In addition, you can use another catch group to get the string. The 1st catch group should match anything that is not a bracket. Use a fallback array in case no match found, and use destructuring to get the string, and the number. If the string/number are undefined
there's no match.
var key = 'value[0]'; var [, str, number] = key.match(/([^\\[]+)\\[([0-9]+)\\]/) || []; console.log({ str, number });
Use another capture group to get the part of the string before the square brackets.
Also, the regexp shouldn't be quoted.
var key = 'value[0]' var matches = key.match(/(\\w+)\\[([0-9]+)\\]/); if (null != matches) { var variable = matches[1]; var num = matches[2]; } console.log(`variable = ${variable}, index = ${num}`);
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.