I was coming up with a few simple tests to exercise your code.
Making the code easier to test
To easily test the code, it helps if the functions require less assumptions. This was easily achieved by moving your conversion code out to a separate syntaxHighlight() function.
function syntaxHighlight(data) {
data = data.replace(/"(.*?)"/g,'<span class="code-str">"$1"</span>');
data = data.replace(/<(.*?)>/g,'<span class="code-elem"><$1></span>');
return data;
}
function syntaxhighlights() {
var ca = document.getElementsByTagName("code");
for(var i=0; i<ca.length; i++){
ca[i].innerHTML = syntaxHighlight(ca[i].innerHTML);
}
}
That way, the syntaxHighlight function can be given a simple string as data, and the returned value can be easily checked.
Testing quote highlight
Here is the quote highlight test:
console.assert(
syntaxHighlight('<h2 id="h2class">') ===
'<h2 id=<span class="code-str">"h2class"</span>>',
"Should highlight quotes"
);
And it works well, only outputting to the console when the test fails.
Testing tag highlight
Here is the tag highlight test:
console.assert(
syntaxHighlight('<p>') ===
'<span class="code-elem"><p></span>',
"Should highlight tags"
);
This test failed, outputting to the console that it should highlight tags.
Was something wrong with my test, or was it the code?
Investigating the cause
We can log out the result from syntaxHighlight to find out more details about things.
console.log(syntaxHighlight('<p>'));
And we get the following output:
<span class="code-elem"><p></span>
Do you see how the >
is missing its semicolon? It should be $gt;
instead.
Let’s investigate the code to find out why that’s happening.
Here is the line responsible:
data = data.replace(/<(.*?)>/g,'<span class="code-elem"><$1></span>');
Fixing the cause of the problem
Near the end of the above line of code where it has ></span>
, that should instead be ></span>
data = data.replace(/<(.*?)>/g,'<span class="code-elem"><$1></span>');
And the asserts no longer log out any problems. The code is now better than it was.
Summary
That has been a good demonstration of using tests. They help to ensure that the code works in expected and desirable ways.
The full code that was used is:
function syntaxHighlight(data) {
data = data.replace(/"(.*?)"/g,'<span class="code-str">"$1"</span>');
data = data.replace(/<(.*?)>/g,'<span class="code-elem"><$1></span>');
return data;
}
function syntaxhighlights() {
var ca = document.getElementsByTagName("code");
for(var i=0; i<ca.length; i++){
ca[i].innerHTML = syntaxHighlight(ca[i].innerHTML);
}
}
window.addEventListener("load", syntaxhighlights);
// Tests
console.assert(
syntaxHighlight('<h2 id="h2class">') ===
'<h2 id=<span class="code-str">"h2class"</span>>',
"Should highlight quotes"
);
console.assert(
syntaxHighlight('<p>') ===
'<span class="code-elem"><p></span>',
"Should highlight tags"
);
The code with the asserts can be found at https://jsfiddle.net/rht5f976/?editor_console=0