Question

string=string.replace(RegExp(filter[a]+" | "+filter[a],"g"),filter[a])

For some reason, this isn't affecting both the filter followed by the space and the filter with a space in front. Assuming the filter is ",", it would take the second side and only replace " ," rather than " ," and ", ". The filter is user-specified, so I can't use a normal regular expression (which DOES work) such as string=string.replace(/, | ,/g,filter[a]) Can someone explain to me why it doesn't work and how to make it work?

Was it helpful?

Solution

It works for me:

s = 'abc, def,ghi ,klm'
a = ','
s = s.replace(RegExp(a + " | " + a, "g"), a)
"abc,def,ghi,klm"

Remember that you regular expression won't replace " , " with ",". You could try using this instead:

" ?" + filter[a] + " ?"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top