Abhishek
Abhishek

Reputation: 2185

Coloring a sub string of a string in JS to be used in html

I am using autocomplete JQuery plugin with html rendition. It's working fine. More over it I want to color the part which exactly equals with the string which I have entered.

My Textbox__________________
| Input                    |
____________________________
: First suggestion         :
: `Input`string            :
:                          :
----------------------------
: Second suggestion        :
: `Input`type              :
:                          :
----------------------------

I want those "Input" in different color.

For Coloring the substring I wrote this function.

String.prototype.colorSubString= function(subStr, hexColorCode) {
    var mainStr_low = this.toLowerCase(); // for case insensitivity
    var subStr_low = subStr.toLowerCase();// for case insensitivity
    if(mainStr_low.indexOf(subStr_low)){
        return this.substring(0, mainStr_low.indexOf(subStr_low)) + 
        "<span style='color:"+  hexColorCode+ "'>"+      
        this.substring(mainStr_low.indexOf(subStr_low), 
        mainStr_low.indexOf(subStr_low)+subStr_low.length)+ 
        "</span>"+    
        this.substring(mainStr_low.indexOf(subStr_low)+subStr_low.length,mainStr_low.length);
    }

        return this;
    }

But things are not working. Am I doing anything wrong? Is there any better, clean solution?

Upvotes: 0

Views: 179

Answers (1)

Yhn
Yhn

Reputation: 2815

http://jsfiddle.net/6yKyx/ << There was a small error, but it works like this.

To elaborate the issue; you have the following code:

if(mainStr_low.indexOf(subStr_low)) {

However; if the substring is at the beginning of the main string; the indexOf returns index 0 (which is equivalent to false).

To fix your function, change that line to:

if(mainStr_low.indexOf(subStr_low) >= 0) {

As requested, A (imho) more cleaner solution: http://jsfiddle.net/6yKyx/1/

This uses the "power" of RegEx and using a callback function to do the final replacing. The end result is the same, while the code is a lot less trouble :). Andohbytheway; this does replace all occurrences of the given substring; if you just want the first; remove the "g" option from the RegEx object constructor :) (leave the "i" for case-insensitive though).

Upvotes: 1

Related Questions