简体   繁体   English

JavaScript Regex捕获和替换

[英]JavaScript Regex capture and replace

I have a string that looks like this: 我有一个看起来像这样的字符串:

var whereClause = "p_id eq @p_id@ and idr_user_id eq @idr_user_id@";

I have the following regular expression to capture the tokens /(@\\w+@)/g 我有以下正则表达式来捕获令牌/(@@ w + @)/ g

I would like to be able to replace each occurrence with a different value something like 我希望能够用不同的值替换每次出现,例如

whereClause.replace(/(@\w@)/g, projectID, userID);

Will this work? 这样行吗? Any Ideas would be helpful... 任何想法都会有所帮助...

You could aim for something like this: 您可以针对这样的目标:

template(string, {key: value, key: value});

It could be implemented in a few lines using the replace callback: 可以使用replace回调在几行中实现:

function template(text, obj) {
  var regex = /@(\w+)@/g;
  return text.replace(regex, function(_, match) {
    return obj[match] || _;
  });
}

// Usage:
var str = 'p_id eq @p_id@ and idr_user_id eq @idr_user_id@';
var result = template(str, {p_id: 123, idr_user_id: 'ABC'});
//^ "p_d eq 123 and idr_user_id eq ABC"

If you need different regex or structure, you can create a simple closure around those, like: 如果您需要其他正则表达式或结构,则可以围绕它们创建一个简单的闭包,例如:

function template(regex, fn) {
  return function (text, obj) {
    return text.replace(regex, function(_, match) {
      return fn.call(obj, match);
    });
  }
};

// Using an array
var myTemplate = template(/%(\d+)/g, function(x) {
  return this[--x];
});
var str = 'Hello %1, foo %2';
var result = myTemplate(str, ['world', 'baz']);
//^ "Hello world, foo baz"

You could do something like: 您可以执行以下操作:

whereClause.replace(/@\w+@/g, function(token) {
    switch (token) {
        case '@p_id@': return projectID;
        case '@idr_user_id@': return userID;
    }
    return token;
});

I've done something somewhat similar to this before for dynamic error messaging. 对于动态错误消息传递,我之前已经做过类似的事情。 To do it with what you are doing, it would go something like this. 要按照您正在做的事情来做,它会像这样。

function populateMessage(messageTemplate, replacementVals) {
    var newMessage = messageTemplate;

    for (var targetVal in replacementVals) {
        if (replacementVals.hasOwnProperty(targetVal)) {
            newMessage = newMessage .replace("@" + targetVal + "@", replacementVals[targetVal]);
        }
    }

    return newMessage;
}

var whereClause = "p_id eq @p_id@ and idr_user_id eq @idr_user_id@";
var replacementText = {"p_id": "SOME_TEXT_1", "idr_user_id": "SOME_TEXT_2"};
var outputValue = populateMessage(whereClause, replacementText);

The one of the pluses of this approach is that you can use different whereClause and replacementText variables for different situations and the replacement will only happen if the .replace finds a match for the defined keys. 这种方法的优点之一的一个是,你可以使用不同的whereClausereplacementText变量,针对不同的情况,如果更换只会发生.replace认定为定义的键匹配。 So: 所以:

var whereClause1 = "p_id eq @p_id@ and idr_user_id eq @idr_user_id@";
var whereClause2 = "p_id eq @p_id@";
var whereClause3 = "idr_user_id eq @idr_user_id@";

. . . could all be "served" by: 可以全部由以下人员“投放”:

var replacementText = {"p_id": "SOME_TEXT_1", "idr_user_id": "SOME_TEXT_2"};

. . . and result in valid messages. 并产生有效消息。

It would also be REALLY easy to populate the replacementText object with dynamic values, if that was needed. 这也将是很容易填充replacementText与动态值的对象,如果需要。

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

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