简体   繁体   English

JavaScript regular Expression从主字符串中提取双qoutes的子字符串

[英]JavaScript regular Expression to extract a substring which is in double qoutes, from a master string

i have a string , which look like an array of strings. 我有一个字符串,看起来像一个字符串数组。 I need a regex pattern in javascript to extract the substrings inside that master string, and return me the substring. 我需要在javascript中使用正则表达式模式来提取主字符串中的子字符串,并返回子字符串。 Look at the string given below, and i need a regex on the basis of this string. 看看下面给出的字符串,我需要一个基于这个字符串的正则表达式。 And the regex will extract the substrings like : files/file/img1.jpg ,files/file/img2.jpg and so on, until the end. 正则表达式将提取子字符串,如:files / file / img1.jpg,files / file / img2.jpg等,直到结束。 As much directories i have , i want them to be extracted. 我拥有尽可能多的目录,我希望它们被提取出来。 For time being just consider that its not an array, its just a string. 暂时只考虑它不是一个数组,它只是一个字符串。 Thank you 谢谢

 str = "["files/file/img1.jpg","files/file/img2.jpg","files/file/img3.jpg","files/file/img4.jpg","files/file/img5.jpg","files/file/img6.jpg"] "; 

Use JSON.parse to parse your string.Then just iterate over the array. 使用JSON.parse来解析你的字符串。然后迭代数组。

 var str = '["files/file/img1.jpg","files/file/img2.jpg","files/file/img3.jpg","files/file/img4.jpg","files/file/img5.jpg","files/file/img6.jpg"]'; var result = JSON.parse(str); for(var i= 0; i< result.length;i++){ console.log(result[i]); } 

The syntax is kinda wrong. 语法有点错误。 It should be: 它应该是:

var str ="[\"files/file/img1.jpg\",\"files/file/img2.jpg\",\"files/file/img3.jpg\",\"files/file/img4.jpg\",\"files/file/img5.jpg\",\"files/file/img6.jpg\"] ";

Apart from that we can just use multiple Javascript string manipulation functions to extract the string: 除此之外,我们可以使用多个Javascript字符串操作函数来提取字符串:

data = str.split('["')[1].split('"]')[0].replace(/"/g, "").split(',');

Now the variable data is an array which has all the directories you need. 现在,变量数据是一个包含所需目录的数组。 The output looks something like this: 输出看起来像这样:

 (6) ["files/file/img1.jpg", "files/file/img2.jpg", "files/file/img3.jpg", "files/file/img4.jpg", "files/file/img5.jpg", "files/file/img6.jpg"]

You can get each directory by indexing it: data[0] is the first one. 您可以通过索引来获取每个目录:data [0]是第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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