简体   繁体   English

JavaScript正则表达式获取引号字符串中的单词

[英]JavaScript Regular Expression to get words in quotes string

Thanks for all, I met a problem in JavaScript, and the problem is: 谢谢大家,我在JavaScript中遇到了一个问题,问题是:

I have a string: such as: 我有一个字符串:例如:

{"results":[{"id":"id1","text":"text1"},{"id":"id2","text":"text2"},{"id":"id3","text":"text3"}]}

Then, I want to get the string such as: 然后,我想获取如下字符串:

id1|text1|id2|text2|id3|text3

So how should I write the Regular Expression? 那我该怎么写正则表达式呢?

Thank you so much, and I am a new comer in StackOverFlow! 非常感谢,我是StackOverFlow的新成员!

I have a string 我有一个弦

That string is in JSON format , which works very well with JavaScript. 该字符串为JSON格式 ,与JavaScript配合得很好。

So how should I write the Regular Expression? 那我该怎么写正则表达式呢?

You should not write a regular expression at all. 您根本不应该编写正则表达式。 If you did, you only had two problems : 如果这样做,您只会遇到两个问题

.replace(/(^.+?|"\\},\\{)?"id":"|","text":"|"}[^"]*$/g, "|").slice(1,-1)

Instead, parse the string into an object, and extract the id-text pairs from there: 相反,将字符串解析为一个对象,然后从那里提取id-text对:

var result = JSON.parse(string).results.map(function(el) {
    return el.id+"|"+el.text;
}).join("|");

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

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