开发者

Removing '+' from a Query String

I have scoured t开发者_StackOverflow中文版he Internet for an answer to this. I have an array of strings that looks something like this:

[0] Cinnamon+Chocolate+Twists
[1] 3.25+Ounce+Croissant 

I need all the '+' characters removed from these strings, and a space inserted instead. The following code does not work:

nameProduct[1] = nameProduct[1].replace("+"," ");

I have tried several variations of the .replace method, but no luck. Any ideas?


You have to use regular expression with the global flag to replace every occurrence of the character (yes, JavaScript behaves weird in this aspect (or let's say unexpected, depending from which other language you come)):

nameProduct[1] = nameProduct[1].replace(/\+/g," ");

Use a loop to do this for every element.

MDC - replace documentation


Update:

Don't use document.write to create HTML. Your code needs a lot of refactoring but this beyond this question. The data is processed correctly, but the generated HTML is not:

<input type="text" size="40" name="Product1401" value="Cinnamon" chocolate="" twists="" readonly="">

You see, you have problems with the quotes. The other parts of the text are recognized as attributes.

A slightly improved version would be (just this part):

var nameProduct = hashes[i].split('=');
var tr = document.createElement('tr');
var td = document.createElement('td');
var input = document.createElement('input');

input.type = "text";
input.size = 40;
input.name = nameProduct[0]      
nameProduct[1] = nameProduct[1].replace(/%/g, '');
nameProduct[1] = nameProduct[1].replace(/2C/g, '');
nameProduct[1] = nameProduct[1].replace(/2F/g, '');
nameProduct[1] = nameProduct[1].replace(/28/g, '');
nameProduct[1] = nameProduct[1].replace(/29/g, '');
nameProduct[1] = nameProduct[1].replace(/\+/g, " ");

input.value = nameProduct[1];
input.readOnly = true;

td.appendChild(input);
tr.appendChild(td);
document.getElementById('gradient-style').tBodies[0].appendChild(tr);

DEMO

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜