Javascript 如何获得位于 2 个引号之间的子字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12367126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:49:58  来源:igfitidea点击:

How can I get a substring located between 2 quotes?

javascriptjqueryregex

提问by Phil

I have a string that looks like this: "the word you need is 'hello' ".

我有一个看起来像这样的字符串:“你需要的词是‘你好’”。

What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?

将 'hello' (但不带引号)放入 javascript 变量的最佳方法是什么?我想这样做的方法是使用正则表达式(我知之甚少)?

Any help appreciated!

任何帮助表示赞赏!

回答by Jo?o Silva

Use match():

使用match()

> var s =  "the word you need is 'hello' ";
> s.match(/'([^']+)'/)[1];
"hello"

This will match a starting ', followed by anything except ', and then the closing ', storing everything in between in the firstcaptured group.

这将匹配一个开始',然后是除之外的任何内容',然后是结束',将其间的所有内容存储在第一个捕获的组中。

回答by F0G

http://jsfiddle.net/Bbh6P/

http://jsfiddle.net/Bbh6P/

var mystring = "the word you need is 'hello'"
var matches = mystring.match(/\'(.*?)\'/);  //returns array

?alert(matches[1]);?

回答by Beetroot-Beetroot

If you want to avoid regular expressions then you can use .split("'")to split the string at single quotes , then use jquery.map()to return just the odd indexed substrings, ie. an array of all single-quoted substrings.

如果您想避免使用正则表达式,则可以使用.split("'")单引号拆分字符串,然后使用jquery.map()仅返回奇数索引子字符串,即。所有单引号子串的数组。

var str = "the word you need is 'hello'";
var singleQuoted = $.map(str.split("'"), function(substr, i) {
   return (i % 2) ? substr : null;
});

DEMO

演示

CAUTION

警告

This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.

如果原始字符串中出现一个或多个撇号(与单引号相同),则此方法和其他方法都会出错。