Your first try
with for loop and if statement:
for(var i=0; i<str.length; i++){
if(str[i]==="&"){
str[i]="&";
}
}
Of course this won't work. JS strings are immutable, which means
Once a string is created, it is not possible to modify it
It won't cause a run-time error, but it won't do anything. (Even if JS strings were not immutable, which they are, you could not replace one character with multiple characters.)
Your second try
with regex and replace:
var myRegExp = /\b&\b/;
str = str.replace(myRegExp,"&");
return str;
Of course this won't work. There is no word boundary between a space and an ampersand. See the definition of word boundary:
A word boundary matches the position where a word character is not followed or preceded by another word-character.
where "word character" is equivalent to [a-zA-Z0-9_].
But why?
However, the real question is why you want to do this. If you simply want to insert this string into the DOM as text, then do so using textContent:
document.getElementById("city").textContent = "Sydney & Melbourne";
(instead of using innerHTML). In jQuery, if you happen to be using that, use text() instead of html(). This approach has the advantage that it won't be confused by other HTML characters in the string, notably <.
If your issue is related to & in a URL, you shouldn't be HTML-escaping it--you should be URI-encoding it, but you probably already knew that.
If your issue is that you are passing this to a server which expects properly encoded HTML strings, then you should reconsider your API design. In general, it's better to store the raw strings on the server, and decode/encode/escape/unescape them when necessary--remember that server data might be displayed in contexts other than browser. If you absolutely do want to send the server properly HTML-escaped strings, then you need to worry about more than just &, but also the other special HTML characters. For this, you should use some utility that is probably available in your favorite library, or the standard:
function htmlEscape(str) {
var div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
\bfrom regex.'Sydney & Melbourne'.replace(/&/g, '&');replace(/&/g, '&)` would not work, whether with double quotes or single quotes.