繁体   English   中英

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

[英]How can I get a substring located between 2 quotes?

我有一个看起来像这样的字符串:“您需要的单词是'hello'”。

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

任何帮助表示赞赏!

使用match()

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

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

使用.split()很简单,(仅)如果您知道索引

 var str = "the word you need is 'hello' world"; console.log( str.split(/'/)[1] ); 

由于.split()将我们的字符串转换为Array,因此[1]索引用于获取确切的键:

[
  "the word you need is ",
  "hello",                          // at index 1
  " world"
]

注意:

上面的代码将失败,即: it'll fail in 'this' case ,其中[1]将给您带来ll fail in而不是预期的this

http://jsfiddle.net/Bbh6P/

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

​alert(matches[1]);​

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

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

演示

警告

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

暂无
暂无

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

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