使用jQuery在括号之间获取文本

时间:2017-12-12 13:24:48

标签: javascript jquery

我试图在以{{

开头的'开头的多个花括号之间获取价值

例如:

var txt ="I expect five hundred dollars {{$500}}. and new brackets {{$600}}";

预期结果:array of result like result[0] = "{{$500}}", result[1] = "{{$600}}"

我尝试了下面的事情,但它没有返回预期的结果

var regExp = /\{([^)]+)\}/g;
var result = txt.match(regExp);

JsFiddle Link

4 个答案:

答案 0 :(得分:2)

您可以使用/{{\w+:(\$\d+)}}/g这样的简单正则表达式,然后使用RegExp#exec函数获取每个匹配项,并从捕获的组中提取值。

var txt = "I expect five hundred dollars {{rc:$500}}. and new brackets {{ac:$600}}";

var reg = /{{\w+:(\$\d+)}}/g,
  m,
  res = [],
  res2 = [];

while (m = reg.exec(txt)) {
  res.push(m[0]);
  res2.push(m[1]);
}

console.log(res,res2)

答案 1 :(得分:1)

使用map/(?:({{))[^}]+(?=}})/g,正则表达式为var txt ="I expect five hundred dollars {{ac:$500}}. and new brackets {{ac:$600}}"; var matches = txt.match( /(?:({{))[^}]+(?=}})/g ); if ( matches ) { matches = matches.map( s => s.substring(2) ); } console.log( matches );

var txt ="I expect five hundred dollars {{ac:$500}}. and new brackets {{ac:$600}}";
var matches = txt.match(/(?:({{))[^}]+(?=}})/g);
if (matches) {
  matches = matches.map(s => s.substring(2));
}
console.log(matches);

<强>演示

{{1}}

答案 2 :(得分:0)

像这样改变你的代码

&#13;
&#13;
var txt ="I expect five hundred dollars {{$500}}. and new brackets {{$600}}";
function getText(str) {
  var res = [], p = /{{([^}]+)}}/g, row;

  while(row = p.exec(str)) {
    res.push(row[1]);
  }
  return res;
}
console.log(getText(txt)); 
&#13;
&#13;
&#13;

答案 3 :(得分:0)

String#match将始终返回完整匹配的正则表达式,而不使用捕获组。您可以使用带有回调函数的String#replace将每个匹配添加到数组中。

&#13;
&#13;
var txt ="I expect five hundred dollars {{ac:$500}}. and new brackets {{ac:$600}}";

var regExp = /{{ac:([^\}]+)}}/g;

function matches(regExp, txt) {
  const result = []
  txt.replace(regExp, (_, x) => result.push(x));
  return result
}

console.log(matches(regExp, txt))
&#13;
<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>
&#13;
&#13;
&#13;