I am working through a book about Javascript and have encountered the following example of code designed to replace the value of the class attribute of a table header HTML element:
th.className = th.className.replace(/asc/,"dsc");
th.className = th.className.replace(/dsc/,"asc");
Why is the first parameter of .replace, the current value of th.className, enclosed in forward slashes instead of quotation marks?
Why not use quotation marks to enclose both parameters, not just the second one?
Those are regular expressions. You can use either regular expressions or strings to define the match criteria for
.replace().For example, if you wanted to replace all occurrences of
'asc'in a string, you could use theg(global) modifier on the regex.But given your examples, the regex used won’t provide any different result than using a string
'asc'.