Okay well I don't see anything in this code that directly replaces anything with a space. My next guess is the dataLayer[0]['pageURL'] variable you reference sometimes has spaces in it. Maybe whatever outputs this data layer variable has it when it is output sometimes. Or maybe there is some other code elsewhere that alters it sometimes. Or, maybe you have other code elsewhere that sets your page name using different code, that executes/overrides this code, sometimes.
I'm not sure what more I can really do to try and help without at least a link to the site to poke at. If you can provide a link to the site (ideally, a page where you see this happening in the reports), I can try and dig deeper into it, but you're definitely getting into "need to be a real coder to QA this" territory. Things like outputting console logs at specific points in DTM, adding breakpoints/watches on variables in the js console.. not really feasible to try and walk you through that stuff on the forums..
Sidenote: At face value it looks like you are piggybacking off of Google Tag Manager's (GTM) dataLayer array. This is generally a bad idea.. mainly because unlike most data layer conventions, GTM pushes data layer states to an array, and there's no guarantee which element in the stack is the one you actually want for a given event. For example I assume you reference dataLayer[0] with the assumption it will contain relevant page view data from initial page load. Well there's no guarantee this will always be the case with GTM. This logic also kinda gets tossed out the window if you have SPA pages, because you are effectively only looking at original full page load data (assuming its even first in the queue).