`(query.indexOf("#") === -1) ? query.replace("&", "&amp;") : query.replace("#", "&#35;")` should be moved to a function since it is used agan below.