473,398 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

JavaScript Keyword Highlighting

After much searching of google, the closest I can find is highlighting
search terms... however, this is not what I wanted to do.

Does anyone know how to parse through a specific element (lets say the
innerHTML of a div) and add tags to change the styles of several
keywords?

For instance, I might want the words "and", "or" and "xor" to be bold
and the words "c_white", "c_red" and "c_orange" to appear as maroon...
(it's for a syntax highlighting script).

It would need to be able to take multiple lists, and if it could load
those lists from an external file that would be great, but an array is
just fine... they keywords lists I am using are quite long.

Thank you
-Leif902

Apr 7 '07 #1
7 2297
es_
Leif902 wrote:
After much searching of google, the closest I can find is highlighting
search terms... however, this is not what I wanted to do.

Does anyone know how to parse through a specific element (lets say the
innerHTML of a div) and add tags to change the styles of several
keywords?

For instance, I might want the words "and", "or" and "xor" to be bold
and the words "c_white", "c_red" and "c_orange" to appear as maroon...
(it's for a syntax highlighting script).

It would need to be able to take multiple lists, and if it could load
those lists from an external file that would be great, but an array is
just fine... they keywords lists I am using are quite long.

Thank you
-Leif902
// http://www.nsftools.com/misc/SearchAndHighlight.htm
// shorter version by TW

function doHighlight(bodyText, searchTerm)
{

highlightStartTag = "<span class='hili' style='
background-color:yellow;'>";
highlightEndTag = "</span>";

var newText = "";
var i = -1;
var lcSearchTerm = searchTerm.toLowerCase();
var lcBodyText = bodyText.toLowerCase();

while (bodyText.length 0) {
i = lcBodyText.indexOf(lcSearchTerm, i+1);
if (i < 0) {
newText += bodyText;
bodyText = "";
} else {
if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
if (lcBodyText.lastIndexOf("/script>", i) >=
lcBodyText.lastIndexOf("<script", i)) {
newText += bodyText.substring(0, i) + highlightStartTag +
bodyText.substr(i, searchTerm.length) + highlightEndTag;
bodyText = bodyText.substr(i + searchTerm.length);
lcBodyText = bodyText.toLowerCase();
i = -1;
}
}
}
}

return newText;
}
function hST(searchText, treatAsPhrase)
{

if (treatAsPhrase) {
searchArray = [searchText];
} else {
searchArray = searchText.split(" ");
}

var bodyText = document.body.innerHTML;
for (var i = 0; i < searchArray.length; i++) {
bodyText = doHighlight(bodyText, searchArray[i]);
}

document.body.innerHTML = bodyText;
return true;
}
// hST("search");

Apr 8 '07 #2
On Apr 8, 5:38 pm, es_ <es_uomikim@ALA_MA_KOTAop.plwrote:
Leif902 wrote:
After much searching of google, the closest I can find is highlighting
search terms... however, this is not what I wanted to do.
Does anyone know how to parse through a specific element (lets say the
innerHTML of a div) and add tags to change the styles of several
keywords?

A basic script is simple, however it becomes complex very quickly:
what do you do with words that are already wrapped in emphasis or
highlighting elements?

e.g.:

<!-- Define highligh classes -->
<style type="text/css">
.animal {color: red;}
.thing {color: blue;}
</style>
<script type="text/javascript">

// Keywords
var keywordObj = {
cat : 'animal',
dog : 'animal',
mat : 'thing',
door : 'thing'
}

function highlightKeywords(el) {
var a = el.innerHTML.split(/\b/);
var w;

for (var i=0, len=a.length; i<len; i++){
w = a[i]

// If word is a keywords, wrap in highlight span
if (w in keywordObj) {
a[i] = '<span class="' + keywordObj[w] + '">'
+ w + '<\/span>';
}
}

// Update the element's innerHTML
el.innerHTML = a.join('');
}

</script>

<button onclick="highlightKeywords(document.getElementById ('p01'),
'cat');">Higlight some words</button>

<p id="p01"onclick="alert(this.innerHTML);">The cat and the
dog went through the door to sit on their mat. The cat on
the cat:mat, the dog on the dog:mat.</p>
If you press the button multiple times, you'll see that the words are
wrapped multiple times. If you want to match cat, cats, Cat, Cats,
you have to add each one to the keywords object.

There is also an interesting post from Yann-Erwan Perio:

<URL:
http://groups.google.com.au/group/co...a8f6630c533340
>
>
For instance, I might want the words "and", "or" and "xor" to be bold
and the words "c_white", "c_red" and "c_orange" to appear as maroon...
(it's for a syntax highlighting script).
It would need to be able to take multiple lists, and if it could load
those lists from an external file that would be great, but an array is
just fine... they keywords lists I am using are quite long.
An array is less functional (how do you allocate different higlighting
for different words?) and searching an array is likely much slower
than using a object with the in operator.
[...]
function doHighlight(bodyText, searchTerm)
{
[...]

That seems long-winded. Consider:
function highlightWord1(el, word, c){
var c = c || '#ff0000';
var re = new RegExp('\\b' + word + '\\b','i');

var s = el.innerHTML;
var newS = '';
while (re(s)) {
newS += RegExp.leftContext + '<span style="color:'+c+';">'
+ RegExp.lastMatch + '<\/span>';
s = RegExp.rightContext;
}
el.innerHTML = newS + RegExp.rightContext;
}
--
Rob

Apr 9 '07 #3
Thank you both, this looks like it will work fine for my purposes
(with a little modification that is)!
-Leif902

Apr 10 '07 #4
>
<!-- Define highligh classes -->
<style type="text/css">
.animal {color: red;}
.thing {color: blue;}
</style>

<script type="text/javascript">

// Keywords
var keywordObj = {
cat : 'animal',
dog : 'animal',
mat : 'thing',
door : 'thing'
}

function highlightKeywords(el) {
var a = el.innerHTML.split(/\b/);
[...]

--
Rob

Rob, I ended up using your method (thanks again)...

Now I have another question though, if anyone can answer it... How
might I, in the same script preferably, format a single line (for
instance a line after //) or multiple lines between two sets of
characters (/**/ c style)? I'm very new to javascript incase you can't
tell :) I'm more of a C++/GML kind of person... but I'm attempting to
learn
-Leif

Apr 11 '07 #5
Edit: Sorry for the multiple posts, but I forgot... also, is it
possible to load a file on the server and read values from it? I don't
know how to load a file, otherwise I would build the list of keywords
dynamically from a list (c_red,c_white or maybe using a linebreak...
whatever, the parsing's not hard, just the file stream :) )

Thanks again
-Leif
Apr 11 '07 #6
On Apr 11, 10:20 am, "Leif902" <leif...@gmail.comwrote:
Edit: Sorry for the multiple posts, but I forgot... also, is it
possible to load a file on the server and read values from it? I don't
know how to load a file, otherwise I would build the list of keywords
dynamically from a list (c_red,c_white or maybe using a linebreak...
whatever, the parsing's not hard, just the file stream :) )
Sure, search the archives, there are a number of methods. The
simplest is to load a script file that contains an object with the
required data, you could also use XMLHttpRequest.
--
Rob

Apr 11 '07 #7
On Apr 10, 10:41 pm, "RobG" <r...@iinet.net.auwrote:
On Apr 11, 10:20 am, "Leif902" <leif...@gmail.comwrote:
Edit: Sorry for the multiple posts, but I forgot... also, is it
possible to load a file on the server and read values from it? I don't
know how to load a file, otherwise I would build the list of keywords
dynamically from a list (c_red,c_white or maybe using a linebreak...
whatever, the parsing's not hard, just the file stream :) )

Sure, search the archives, there are a number of methods. The
simplest is to load a script file that contains an object with the
required data, you could also use XMLHttpRequest.

--
Rob
Okay, thank you, i'll look into that
- Leif

Apr 11 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Alex Fitzpatrick | last post by:
Just by way of introduction, I'm currently the principal developer and maintainer of the a JavaScript editor plug-in for Eclipse. https://sourceforge.net/projects/jseditor/ The plug-in as it...
7
by: Matthew | last post by:
I am very new to JavaScript, and have been using Notepad. Is there a editor out there that showes the JavaScript environment variables? Example: I just found out about the document.forms array...
1
by: John Smith | last post by:
Can you tell me why Mozilla can't show some Javascript? example: function high(which2){ theobject=which2 highlighting=setInterval("highlightit(theobject)",50) } function low(which2){...
1
by: Paul Aspinall | last post by:
Can anyone recommend a good editor for coding Javascript?? ie. once which has 'intellisense' type prompting etc. If there isn't an editor with this built-in, is there a program which does it as...
3
by: Jane D | last post by:
I have got a bookmarklet for use with Opera which highlights all occurrences of some text in the displayed page. I find it very useful. Sometimes I need to use two or three different colours...
3
by: gil | last post by:
Hi, In VS 2005 (SP1), the following code does not compile: ============= typedef int _sptr ; _sptr p = 1; ============= the compiler emits the following:
1
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause...
2
by: PJ6 | last post by:
Years ago I looked for a text editor control that would do automatic keyword highlighting, to no avail. I found sample code to roll my own, but all of that was crap (mostly because of the way the...
1
by: alamodgal | last post by:
hiiiiiii I have a problem in highlighting searching keyword.Actually im using this function for searching Public Function HighLight(ByVal Keyword As String, ByVal ContentFor As String) Dim...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.