Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 324
gdex Avatar asked Dec 20 '22 19:12

gdex


2 Answers

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;
});
like image 44
rid Avatar answered Jan 09 '23 11:01

rid


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:

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"
like image 131
elclanrs Avatar answered Jan 09 '23 13:01

elclanrs