Bysander Bysander - 6 months ago 18
jQuery Question

Using replace(), global modifier and escaped chars causing comments

having used the internet before I can work out that

replace()
only replaces the first instance of what you're looking for in a string.

Looking at this question, this question and this question to name a few I know that you have to use the
/x/g
if you want to search & replace the whole string for
x
.

My problem is that I'm searching for two characters that get confusing. The asterisks and slash which trigger comments when either of them are used used too close together.

I haven't ever learnt JavaScript so if this is simple I do apologise but I have tried so many different versions of the below I honestly can't remember them all.

$('#answer').delay(1000).each(function(){
$this = $(this);
$this.html($this.html().replace(/\*/g, 'x').replace(/\/\/g, '÷'));
});


When used like this
.replace('*', 'x').replace('/', '÷')
it works fine for just one result.

All help appreciated.

Answer

This works exactly as you described, so if you're having problems look somewhere else. You just wrote an incorrect regular expression and did not read into the errors :) Regular expressions have to be between / symbols and those do not need escaping under any circumstance.

....replace(/\//g, '÷').replace(/\*/g, 'x');

"5*4/2=10".replace(/\//, '÷').replace(/\*/, 'x');
// returns "5x4÷2=10"

In some cases using new RegExp objects would provide better readibility, but in your case that might be clunky.

"5*4/2=10".replace(new RegExp('/', 'g'), '÷').replace(new RegExp('\\*', 'g'), 'x');