Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Finding Comments and Strings With Javascript and innerHTML

Last post 02-23-2010, 9:17 PM by Peadarin. 1 replies.
Sort Posts: Previous Next
  •  02-06-2010, 1:12 AM 59333

    Finding Comments and Strings With Javascript and innerHTML

    Hey guys,

    Alright so I'm trying to create a regular expression for finding comments and (" (wildcard) ") strings inside a javascript file. But I guess doing it this way is a little different than you would normally do it.Here is my javascript file (apart from the array of words it's pretty small) http://cplusdev.com/js/highlighter.js - Anyway as you can see I have an array of what I want to find and what I want to replace it with: 
     
    window.onload = function () 
    {
    var codeBox = document.getElementsByClassName("code");

    var find = [ '\\b' + "bool" + '\\b',
    '\\b' + "break" + '\\b',
    '\\b' + "case" + '\\b'];

    var desc = [ "\<font color=\"0077FF\"\>bool\</font\>",
    "\<font color=\"0077FF\"\>break\</font\>",
    "\<font color=\"0077FF\"\>case\</font\>"];
    for( var i = 0; i < codeBox.length; i++ )
    {
    wordhighlight(codeBox[i], find, desc);
    }
    };

    document.getElementsByClassName("code"); finds all my css divs i created called "code" so I'm only searching inside the code boxes.

    function wordhighlight(aSourceObject, sWords, sDescrip)
    {
    var sText = aSourceObject.innerHTML;
    for( var i = 0; i < sWords.length; i++ )
    {
    sText = sText.replace( new RegExp(sWords[i], "g"), sDescrip[i]); 
    }

    aSourceObject.innerHTML = sText;
    };

    Now this function here works quite well for now as it finds all the keywords I need and replaces them. But obviously I can't figure out how to search for comments/strings and replace them with the color green/red in my javascript. So with the help of a regular expression. Does anyone know how I can search the out and replace them in this particular problem? I Tried " /\*[\d\D]*?\*/ " for searching for comments but no luck on getting it working and replacing the original text.

    Thanks a heap,
    Myth.
  •  02-23-2010, 9:17 PM 60032 in reply to 59333

    Re: Finding Comments and Strings With Javascript and innerHTML

    Your expression is correct  , but javascript might require much more \\, \\ \\\ and \\\\ and so on :-)

    Would the following be more accurate in a javascript script ?

     /\\*[\\d\\D]*?\\*/

     

View as RSS news feed in XML