字符串替换在javascript中不起作用
我的字符串='在购买高于Rs的T恤时获得50%的折扣。 1200&#39 ;;
输出字符串=' get-flat-50%-off-on-tees-purchase-above-rs.-1200';
这是我的js代码。
var json, xhr = new XMLHttpRequest();
xhr.open("GET","http://www.exmaple.com/api/v1.0/deal/deallimit/6/61f4279fb0cb4d4899810bef06539d06e349",true);
xhr.onload=function() {
var response=xhr.responseText;
var resultValue = JSON.parse(response);
var dealArray = resultValue['All deals'];
console.log(dealArray.length);
var i;
for (i = 0; i < dealArray.length; i++)
{
var key1 = 749;
var key2 = 29;
var orgProID = (dealArray[i]['productid']+dealArray[i]['productkey'])/key2;
var cat = dealArray[i]['categoryname'].toLowerCase();
var catReplace = cat.replace(" ","-");
var pro1 = dealArray[i]['productname'].toLowerCase();
var proReplace = pro1.replace('%','-percent');
var proReplace1 = proReplace.replace(" ","-");
console.log(catReplace+"/"+proReplace1);
if (dealArray[i]['price'] !=0) {
document.getElementById('appendDeals').innerHTML +="<tr><td class='dealName'>"+dealArray[i]['productname']+ " @ Rs."+dealArray[i]['price']+"</td><td class='buyDeal'>BUY</td></tr>";
}
else{
document.getElementById('appendDeals').innerHTML +="<tr><td class='dealName'>"+dealArray[i]['productname']+"</td><td class='buyDeal'>BUY</td></tr>";
}
}
}
xhr.send(null);
但是当我在登录控制台日志中找到我
时get-upto 50-percent off on health & personal care products
所有地方都没有被&#39; - &#39;
取代如何做到这一点。
答案 0 :(得分:6)
您的代码无法运行,因为.replace()
不会在字符串内全局替换。您需要设置g
标志以使其全局工作。
按照这个简单的算法获取所需的字符串:
.toLowerCase()
.replace()
%
与-percent
.replace()
空格-
,全局工作代码段:
var myString = 'Get Flat 50% off on Tees Purchase above Rs. 1200';
// apply the algorithm here:
var outputString = myString.toLowerCase().replace('%', '-percent').replace(/ /g,"-");
alert(outputString);
答案 1 :(得分:0)
您需要在全球范围内使用replace
,例如
var proReplace = pro1.replace(/%/g,'-percent');
var proReplace1 = proReplace.replace(/ /g,'-');
答案 2 :(得分:-1)
proReplace.replace(&#34;&#34;,&#34; - &#34;);仅适用于第一次出现的子串。请看这里Replace multiple characters in one replace call