0

given string is

var strg = "RoomItemsQuantity[items][1][itemId]"

I'm having the above string value.How can i get itemId from the string.

var index = strg.lastIndexOf("[");
var fnstrg = strg.substr(index+1);
var fnstrg = fnstrg.replace("]","");

I've done like this is there any easiest way to do this?

thanks,

2
  • Is [1] portion fixed..? Commented Jun 4, 2014 at 11:15
  • Is itemId part of the string or you are showing that as a placeholder for some value? Commented Jun 4, 2014 at 11:19

3 Answers 3

2

This code...

var arr = "RoomItemsQuantity[items][1][itemId]".replace(/]/g, "").split("[")

Will result in an array like this:

["RoomItemsQuantity", "items", "1", "itemId"]

Then...

arr[arr.length - 1]

Will give you what you want.

Sign up to request clarification or add additional context in comments.

Comments

1

If the above pattern is fixed, then you could use the following trick :

var myString = "RoomItemsQuantity[items][1][itemId]";
var myItemId = (myString+"[").split("][")[2]

Comments

1

You can use a regular expression like:

('RoomItemsQuantity[items][1][itemId]'.match(/([^\[]+)\]$/) || [])[1] // itemId

You can also use lookahead or lookbehind but support may not be available.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.