如何检查字符串是否包含数组中的某些字符串然后替换它?

时间:2015-12-22 09:09:21

标签: javascript

我有这样的信息:

  

“越来越近!只有$:is_left_to_reach_cart_total_goal远离   免费送货!“

我需要用实际数字替换:is_left_to_reach_cart_total_goal。此外,邮件还可以包含其他变量,例如:cart_total_currently , :cart_total_goal , :cart_products_quantity_currently , :cart_products_quantity_goal , :is_left_to_reach_products_quantity_goal , :link , :button .

任何建议?

3 个答案:

答案 0 :(得分:1)

这会将您的变量替换为' 2'。

var str = "Getting Closer! Only $:is_left_to_reach_cart_total_goal away from FREE SHIPPING!";
var res = str.replace("$:is_left_to_reach_cart_total_goal", "2");

JavaScript String replace() Method

答案 1 :(得分:0)

这会将original字符串替换为number

var original = "Getting Closer! Only $:is_left_to_reach_cart_total_goal away from FREE SHIPPING!";
var number = 1;
var newone = original.replace(/:is_left_to_reach_cart_total_goal/g, number);

你也可以创建一个你想要替换的占位符和值数组,然后像这样减少它:

var original = "Getting Closer!"
             + "Only $:is_left_to_reach_cart_total_goal away from FREE SHIPPING!"
             + "Additional info: $:link";

var toReplace = [
    { key: ":is_left_to_reach_cart_total_goal", value: "1" },
    { key: ":cart_total_currently", value: "2" },
    { key: ":cart_total_goal", value: "3" },
    { key: ":cart_products_quantity_currently", value: "4" },
    { key: ":cart_products_quantity_goal", value: "5" },
    { key: ":is_left_to_reach_products_quantity_goal", value: "6" },
    { key: ":link", value: "7" },
    { key: ":button", value: "whateverelse" }
];

var result = toReplace.reduce(function(r, item) {
    return r.replace(new RegExp(item.key, "g"), item.value);
}, original);
console.log(result);

注意:使用 g 标志替​​换所有出现的字符串。

答案 2 :(得分:0)

您可以拥有一个对象,该对象具有可以出现在字符串中的键并保存其值并使用循环替换它。以下是一个例子:

JSFiddle

function splitStr(str, seperator) {
  return str.split(seperator)
}

function main() {
  var str = "Getting Closer! Only $:cart_total_currently , $:cart_total_goal , $:cart_products_quantity_currently , $:cart_products_quantity_goal , $:is_left_to_reach_products_quantity_goal , $:link , $:button away from FREE SHIPPING!";

  var valueObj = {
    "cart_total_currently": 100,
    "cart_total_goal": 200,
    "cart_products_quantity_currently": 2,
    "cart_products_quantity_goal": 5,
    "is_left_to_reach_products_quantity_goal": 3,
    "link": "www.google.com",
    "button": "<a href='www.google.com'>link</a>"
  }

  var arrStr = splitStr(str, '$:');
  var resultStr = replaceStr(arrStr, valueObj);
  console.log(resultStr);
}

function replaceStr(arr, obj) {
	var retStr = "";
	arr.forEach(function(row){
  	var key = row.split(" ")[0];
    if(obj.hasOwnProperty(key)){
    	retStr += row.replace(key,obj[key]);
    }
    else{
    	retStr += row;
    }
  });
  return retStr;
}
main();