简体   繁体   中英

Get specific part of string between specific characters

I have my string variable source.Changes , which stores different strings. For example, it can store values like these:

[["DriveTypeId",1,2]]
[["LocationId",null,3]

Basically I would like to get the part between the " " characters. So from [["DriveTypeId",1,2]] I would get DriveTypeId .

So far I have tried codes like this source.Changes.split("")[0] but with no luck.

Any idea how to solve this?

Thank you in advance.

You could parse the JSON compliant string and get the value.

 var string = '[["DriveTypeId",1,2]]', parsed = JSON.parse(string), value = parsed[0][0]; console.log(value); 

You can use a regular expression with a capture group:

 const str = '[["DriveTypeId",1,2]]'; const match = /"([^"]+)/.exec(str); if (match) { console.log(match[1]); } 

Or if you can target environments with look-behind, you don't need a capture group:

 const str = '[["DriveTypeId",1,2]]'; const match = /(?<=")[^"]+/.exec(str); if (match) { console.log(match[0]); } 


Note that both of those assume there are no escaped " within the string. If this is valid JSON as I wrestled a bear once observes it might be , use JSON.parse instead.

If you are correct and indeed the stored value is actually a string, you can just do

source.Changes.split('"')[1]

example:

'[["DriveTypeId",1,2]]'.split('"')[1] returns "DriveTypeId"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM