简体   繁体   中英

javascript - .replace() is working on one string but not another

Pulling data with AJAX, into an array, everuthing there works fine, then I have this...

$.each(data, function (key, value){ 
            var add = value[5]+value[6];
            var sub = add.replace(" ","");
            var link = 'http://'+sub+'.mydomain.com';
}

//OUTPUT: http://RR1 Box 22USHIGHWAY 67.NextHomeTown.com

This isn't working. It's not replacing any space characters.

Now, here's where it gets fun. This works on every other DB entry that is returned that has a space. Crazy, right?

Is there some type of character encoding that might be causing it not to recognize the space character that is used in this particular entry? The MySQL table has them entered as varchar , but at this point in the process, they're both just text strings right? So it shouldn't matter.

This will only replace the first spacebar it will match. Use this to replace all spacebars:

var sub = add.replace(/\s/g,"");

Since you report the desired behaviour with other tables, it's perhaps not relevant - but don't forget that in javascript, the string replace function only replaces the first instance of the searchString, unless you use a regular expression.

"red, red, red".replace(/ /g, "");
"red,red,red"

"red, red, red".replace(" ", "");
"red,red, red"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM