I have the String "Edit[user]", but I need get "Edit" and later "user".
How can I do it? Any help would be useful.
Of course I need do it with JavaScript regex.
I have the String "Edit[user]", but I need get "Edit" and later "user".
How can I do it? Any help would be useful.
Of course I need do it with JavaScript regex.
var regex = /(.+)\[(.+)\]/;
var str = "Edit[user]";
regex.exec(str); // will return ["Edit[user]", "Edit", "user"]
或者您可以使用以下String#split
方法这样做:
var str = "Edit[user]";
str.split(/\[(.+)\]/); // will return ["Edit", "user"]
您正在寻找的是分组。我将快速解释这些在 JavaScript 中是如何工作的,并将实际的正则表达式留给你。
var myString = "cat dog frog";
var myRegexp = /(cat).*(frog)/g;
var match = myRegexp.exec(myString);
match 将是一个数组,索引 0 将具有整个匹配项,任何其他将具有组的内容。
match[0] = "cat dog frog"
match[1] = "cat"
match[2] = "frog"