RegExp help needed
Posted: 30 November 2008 04:49 AM   [ Ignore ]
Jr. Member
RankRank
Total Posts:  43
Joined  2008-10-29

Hey! I have got a problem with some js regexp code. I thought Espresso is all about RegExp so this may be the right place to ask. If it’s not ok, please delete this topic.

My goal is: I want to highlight some words with JavaScript.
I’m using mootools.

function highlightWords() {
        
var searchFor = $$('.s').get('value');                    // get search term √ works
        
var searchRegex = new RegExp("("+searchFor+")","gi");    // get regex √ works
        
var results documentText.match(searchRegex);            // match it √ works
        
        
for (0results.lengthi++) {
            
// every single match √ works
            // don't know what goes here, this might be useful.
        
}
        
        
// apply highlights
        // CSS does the theming
        
newDocText originalRendered.replace(searchRegex"<span class='highlight'>"+searchFor+'</span>');
        $$(
'.rendered').set('html'newDocText);
        
        
// STOP, here's the problem. When I search for “m”, it is not case sensitive.
        // So every “M” gets a wrap but will be displayed as “m”.
        
        // apply results
        
resultsText = (results.length == 1) ? " Result" " Results";
        $$(
'#results').set('text'results.length+resultsText);
    

The replacing replaces everything with either lowercase or uppercase terms. I want to search for ‘m’ and it replaces ‘m’ with ‘m’ and ‘M’ with ‘M’.

If anyone knows how to correct this, I would appreciate it.

Thanks!

 Signature 

Markdown.sugar – The super-awesome Markdown for Espresso.

Profile
 
 
Posted: 01 December 2008 09:49 PM   [ Ignore ]   [ # 1 ]
Newbie
Rank
Total Posts:  2
Joined  2008-11-19

Well the i flag signifies case-insensitive matching. Remove the i flag and it will find “M” when “M’ is supplied and same for lowercase “m” will find “m”.
This of course requires that the user or what ever is using the function use the proper case.  But you are probably looking for the use case were you supply an “m” and
you still want the uppercase “M”‘s to be wrapped but not loose case. In that case you would keep the “i” but replace from the match array and not “searchFor”.
—Tstrokes

Profile
 
 
Posted: 02 December 2008 08:19 AM   [ Ignore ]   [ # 2 ]
Jr. Member
RankRank
Total Posts:  43
Joined  2008-10-29

Thanks, that’s exactly what I want to do, type in ‘m’ and every ‘m’ and ‘M’s get wrapped.

But how do I use the match array? It has to do something with for() and match[i].
So I have to replace the first catch with the first match, the second catch with the second match …
I really don’t know how to do this.

 Signature 

Markdown.sugar – The super-awesome Markdown for Espresso.

Profile