最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get quoted text inside a string? - Stack Overflow

programmeradmin7浏览0评论

I have a string like this:

var examplestring = 'Person said "How are you doing?" ';

How can I get the string inside the double quotes. Specifically, I want a var that is set to How are you doing? in this case.

I have a string like this:

var examplestring = 'Person said "How are you doing?" ';

How can I get the string inside the double quotes. Specifically, I want a var that is set to How are you doing? in this case.

Share Improve this question edited Jan 13, 2013 at 2:33 Lee Taylor 7,98416 gold badges37 silver badges53 bronze badges asked Jan 13, 2013 at 2:20 RishaRisha 1472 silver badges7 bronze badges 2
  • What about if the string is 'Person said "How are you doing?" and then said "any better?" '; ? – Lee Taylor Commented Jan 13, 2013 at 2:24
  • 1 In my case, I can ensure there is only one set of double quotes in the string. – Risha Commented Jan 13, 2013 at 2:25
Add a ment  | 

3 Answers 3

Reset to default 4

One way would be to use regular expressions:

var match = exampleString.match(/"([^"]*)"/);

if(match) {
  var quoted = match[1]; // -> How are you doing?
} else {
  //no matches found
}
var quotedString = examplestring.split('"')[1];

This will split on each ", into the following

quotedString[0] = "Person said ";
quotedString[1] = "How are you doing?"
quotedString[2] = " ";

And then select from index 1 of the new array, returning "How are you doing?" (without the quotes).

https://developer.mozilla/en-US/docs/JavaScript/Reference/Global_Objects/String/split

var examplestring = 'Person said "How are you doing?" ';
var extract = examplestring.match(/\"(.*)\"/);
alert(extract[1]);
发布评论

评论列表(0)

  1. 暂无评论