I need to extract from string
userAllowedCrud['create']
the part that is inside[]
.
i think using regular expression is the better way to do it. Am i wrong?
I need to extract from string
userAllowedCrud['create']
the part that is inside[]
.
i think using regular expression is the better way to do it. Am i wrong?
For the example string, you could use split which will return an array and specify the single quote '
as the separator.
Your value will be the second item in the array.
var string = "userAllowedCrud['create']";
console.log(string.split("'")[1]);
If you want to use a regex you could use:
^[^\[]+\['([^']+)']$
or \['([^']+)']
Your value will be in group 1
The first regex will match:
^ # Begin of the string [^[]+ # Match not [ one or more times [' # Match [' ( # Capture in a group (group 1) [^']+ # Match not a ' one or more times ) # Close capturing group '] # Match '] $ # End of the string
The second regex captures in a group what is between ['']
without ^
and $
var string = "userAllowedCrud['create']";
var pattern1 = /^[^\[]+\['([^']+)']$/;
var pattern2 = /\['([^']+)']/
console.log(string.match(pattern1)[1]);
console.log(string.match(pattern2)[1]);
You could use a regular expression like: /\[([^\]]*)\]/
. \[
means match a [
, \]
means match a ]
, [^\]]*
means match 0 or more of any character that is not a close bracket.
console.log(
"userAllowedCrud['create']".match(/\[([^\]]*)\]/)[1]
);
// Output:
// 'create'
If you need what is inside the quotes inside the brackets there are many solutuions, for example:
// for single and double quotes
"userAllowedCrud['create']".match(/\[([^\]]*)\]/)[1].slice(1, -1)
// Or (for single and double quotes):
"userAllowedCrud['create']".match(/\[("|')([^\]]*)\1\]/)[2]
// Or (for single and double quotes):
"userAllowedCrud['create']".match(/\[(["'])([^\]]*)\1\]/)[2]
// Or (for single quotes):
"userAllowedCrud['create']".match(/\['([^\]]*)'\]/)[1]
// Or (for double quotes):
"userAllowedCrud['create']".match(/\['([^\]]*)'\]/)[1]
There are many other methods, these are just a few. I'd recommend looking into learning regex: https://stackoverflow.com/a/2759417/3533202
Try to use javascript string operation
let tempString = "userAllowedCrud['create']";
let key = str => str.substring(
str.indexOf("'") + 1,
str.lastIndexOf("'")
);
console.log(key(tempString))