具有特定前缀和文本的Javascript string.match

时间:2018-01-25 13:56:06

标签: javascript regex

也许有人可以帮我从字符串中获取零件数据。

let input1: string = "any string before specialPrefix: ['content1', 'content2'] and any other text after";  
let input2: string = "any string before specialPrefix:['content1', 'content2'] and any other text after";  
let input3: string = "any string before specialPrefix: 'content1', 'content2' and any other text after";  

预期

output1,output2:包含两个值的数组, '内容1'和' content2'。
output3:空数组

1 个答案:

答案 0 :(得分:0)

您可以使用/specialPrefix:\s*(\[.*?\])/

let inputs = ["any string before specialPrefix: ['content1', 'content2'] and any other text after","any string before specialPrefix:['content1', 'content2'] and any other text after","any string before specialPrefix: 'content1', 'content2' and any other text after"];  
var result = inputs.map(str => (/specialPrefix:\s*(\[.*?\])/.exec(str) || [])[1]);
console.log(result);