String replace is not working in javascript
My string = 'Get Flat 50% off on Tees Purchase above Rs. 1200';
output string = 'get-flat-50-percent-off-on-tees-purchase-above-rs.-1200';
here is my js code.
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);
But when i check in console log i found
get-upto 50-percent off on health & personal care products
all the places are not replaced by '-'
How to do this.
-
your log does not contain "/" are you sure you are posting correct log?webduvet– webduvet2014年12月12日 11:43:34 +00:00Commented Dec 12, 2014 at 11:43
-
Please find the answers below and mark one as accepted if it solves your problem.Rahul Desai– Rahul Desai2014年12月12日 12:04:02 +00:00Commented Dec 12, 2014 at 12:04
3 Answers 3
Your code isnt working because .replace() doesnt do the replacement globally inside the string. You need to set the g flag to make it work globally.
Follow this simple algorithm for getting the string converted as you want:
- Make the whole string
.toLowerCase() .replace()the%with-percent.replace()the space with a-, globally
Working Code Snippet:
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);
Readup: .replace() | MDN, .toLowerCase() | MDN
Comments
You need to use replace in a global sense e.g.
var proReplace = pro1.replace(/%/g,'-percent');
var proReplace1 = proReplace.replace(/ /g,'-');
Have a look at JavaScript Replace.
Comments
The proReplace.replace(" ","-"); only works for the first occurrence of substring. Take a look at here Replace multiple characters in one replace call