[英]JavaScript Regex capture and replace
我有一個看起來像這樣的字符串:
var whereClause = "p_id eq @p_id@ and idr_user_id eq @idr_user_id@";
我有以下正則表達式來捕獲令牌/(@@ w + @)/ g
我希望能夠用不同的值替換每次出現,例如
whereClause.replace(/(@\w@)/g, projectID, userID);
這樣行嗎? 任何想法都會有所幫助...
您可以針對這樣的目標:
template(string, {key: value, key: value});
可以使用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"
如果您需要其他正則表達式或結構,則可以圍繞它們創建一個簡單的閉包,例如:
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"
您可以執行以下操作:
whereClause.replace(/@\w+@/g, function(token) {
switch (token) {
case '@p_id@': return projectID;
case '@idr_user_id@': return userID;
}
return token;
});
對於動態錯誤消息傳遞,我之前已經做過類似的事情。 要按照您正在做的事情來做,它會像這樣。
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);
這種方法的優點之一的一個是,你可以使用不同的whereClause
和replacementText
變量,針對不同的情況,如果更換只會發生.replace
認定為定義的鍵匹配。 所以:
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@";
。 。 。 可以全部由以下人員“投放”:
var replacementText = {"p_id": "SOME_TEXT_1", "idr_user_id": "SOME_TEXT_2"};
。 。 。 並產生有效消息。
這也將是很容易填充replacementText
與動態值的對象,如果需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.