Search code examples
javascriptjqueryreplaceall

Javascript replace all string contains '[]' doesn't work


I am trying this code

RowHTML = RowHTML.replace(/[0]/g, '[' + (LastIndex + 1) + ']');

but it doesn't work, totally ignores the [] and replace every 0 with the [new_number]

any solution ?


Solution

  • [ and ] are special characters in regular expressions. They delimit a character class. If you want to match them literally, you need to escape them in the pattern like this:

    RowHTML = RowHTML.replace(/\[0\]/g, '[' + (LastIndex + 1) + ']');
    

    Or as Fabricio suggests, you only really need to escape the [:

    RowHTML = RowHTML.replace(/\[0]/g, '[' + (LastIndex + 1) + ']');