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
How can I get a substring located between 2 quotes?
提问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
回答by F0G
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;
});
CAUTION
警告
This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.
如果原始字符串中出现一个或多个撇号(与单引号相同),则此方法和其他方法都会出错。