Javascript RegEx匹配字符后的字

时间:2015-03-04 09:48:33

标签: javascript arrays regex

我一直在寻找好几个小时试图解决这个问题,也许我可以睡觉了。我试图RegEx部分字符串,并将其替换为取决于字符后面的单词的值。

" content.size |价格:$ content.price" 我想要做的是使用RegEx用一个值替换我的字符串部分。 我想定位整个表达式content.size和content.price。但是"内容之后的词。"可以是任何东西。我试着写一个表达但没有运气

var firstString = "content.size | price: $content.price"
var Re = new RegExp(/content.\b/);
var newValue = firstString.match(Re);
console.log(newValue);

在这里输入代码我希望从控制台获得的是:

content.size content.price

那么我可以说:

firstString.replace(newValue, someOtherValue)

2 个答案:

答案 0 :(得分:1)

你可以使用替换器功能,虽然我不是100%确定我的问题是正确的

var firstString = "content.size | price: $content.price"
var regex = new RegExp(/content\.([^ ]*)/g);
var newValue = firstString.replace(regex,function(match, group1){
    if(group1 === 'size'){
        // do something with size here
        return '12';
    }
    // return key if not handled
    return group1;
});
console.log(newValue);

<强>更新

似乎问题是如何动态更新尺寸和价格这里是一个更完整的例子。

var data = {size : "12", price : "$ 15.99"};
var firstString = "$content.size | price: $content.price"
var regex = new RegExp(/\$content\.([^ ]*)/g);
var newValue = firstString.replace(regex,function(match, group1){
    if(group1 in data){
        return data[group1];
    }
    // return key if no data present
    return group1;
});
console.log(newValue);

我希望这更清楚。

答案 1 :(得分:0)

你的正则表达式的一个问题是你没有转义小数点(。),它与除换行符之外的任何单个字符相匹配 - 文档在这里:https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

我尝试过以下内容,它返回一个content.size和content.price

数组

您可以尝试一下,看看它是否对您有所帮助:

var firstString = "content.size | price: $content.price";
var regex = /content\.[\S]+/g;
var newValue = firstString.match(regex);
console.log(newValue);

让我知道它是否对你有所帮助。

SO1