marc marc - 7 months ago 25
Javascript Question

split string which has brackets in it

i have a string which contains square brackets [] in it. I want to split that,so that I can get the number contains in it..

String st = "userList[0].name"
String st1 = "userList[1].name"

help me in getting the effective way to get the number both in java/javascript.


You can use split() with a regEx in both, JavaScript and Java to perform the split operation using multiple delimiters.

Here is an example in JavaScript:

// JavaScript
"userList[0].name".split(/[\[\]]+/)[1] // 0

And a very similar approach in Java:

// Java
String string = "userList[0].name";
String result = st.split("[\\[\\]]")[1]; // 0

Assuming that you will have a consistent string structure.

For general bracket content extraction from a string using Java, check out this answer.