What I am trying to do: As stated in the title, I want to set the CSS of a word if it is a reserved word.
<html>
<body>
<code id="java">
public static void main(String[] args)<br>
{
<pre> System.out.println("Hello World!");</pre>
}
</code>
</body>
</html>
$(document).ready(function()
{
// Get the text inside the code tags
var code = $("#java").text();
// Split up each word
var split = code.split(' ');
// Array of reserved words
var array = ["abstract","assert","boolean","break","byte","case",
"catch","char","class","const","continue","default",
"do","double","else","else if","enum","extends","final",
"finally","float","for","goto","if","import","implements",
"instanceof","int","interface","long","native","new","null",
"package","private","protected","public","return","short",
"static","strictfp","super","switch","synchronized","this",
"throw","throws","transient","void","volatile","while"];
// Added when text contains a reserved word
var css = {'font-weight':'bold','color':'#2400D9'}
array = jQuery.map(array, function(n,i)
{
for (int j=0; j<array.length; j++)
{
if (split[i].contains(array[j]))
split[i].css(css);
}
});
});
.split()
even a method in jQuery?for
loop to run through all the words in the array (to see if the code contains a reserved word) or is there a better approach (such as .each()
)?.each()
, could someone please give me a simple example? I don't understand the examples in the documentation..split()
in jQuery.map()
.each()
If I understood correctly, you can achieve what you want using $.inArray
and wrapping the reserved word with a span
tag. See my DEMO
Edit: Below is from jQuery $.inArray documentation.
$.inArray( value, array [, fromIndex] )
-valueThe value to search for.
arrayAn array through which to search.
fromIndexThe index of the array at which to begin the search. The default is 0, which will search the whole array.
..read more..
CSS
.code {
font-weight: bold;
color: #2400D9;
}
JS
$(document).ready(function() {
// Get the text inside the code tags
var code = $("#java").html();
// Split up each word
var split = code.split(' ');
// Array of reserved words
var array = ["abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "else if", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "import", "implements", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "void", "volatile", "while"];
for (var j = 0; j < split.length; j++) {
if ($.inArray(split[j], array) > 0) {
split[j] = '<span class="code">' + split[j] + '</span>';
}
}
$("#java").html(split.join(' '));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With