正则表达式JavaScript

use*_*729 3 javascript regex string node.js

所以我试图用matchResult对象中的适当值替换以下url:

var matchedResult={
  "username": "foo",
  "token": "123"
}

var oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

var matchedResult={
  "username": "foo",
  "token": "123"
}

var match,
regex = /#\{(.*?)\}/g,
oURL = "https://graph.facebook.com/#{username}/posts?access_token=#{token}";
while (match = regex.exec(oURL)) {
    oURL.replace(match[0], matchedResult[match[1]])
}

console.log(oURL);
Run Code Online (Sandbox Code Playgroud)

但结果却是

" https://graph.facebook.com/# {username}/posts?access_token =#{token}"

代替

https://graph.facebook.com/foo/posts?access_token=123

我在这做错了什么?

the*_*eye 6

String.prototype.replace不修改原始字符串,因为JavaScript的字符串是不可变的,但返回一个新的String对象.引用MDN,

replace()方法返回一个新的字符串,其中一些或所有匹配的pattern替换为a replacement.

所以,你需要分配的结果replaceoURL,让老替换还在oURL,这样

oURL = oURL.replace(match[0], matchedResult[match[1]]);
Run Code Online (Sandbox Code Playgroud)

ECMAScript 2015(ECMAScript 6)这样做的方式

如果您所处的环境支持ECMA Script 2015的准字符串文字/模板字符串,那么您可以这样做

`https://graph.facebook.com/${matchedResult.username}/posts?access_token=${matchedResult.token}`
Run Code Online (Sandbox Code Playgroud)

注意:末尾的反引号是新语法的一部分.

使用Babel进行在线演示