2

I have a code like this

(function($, window, document, undefined) {
    $.fn.quicksearch = function (target, opt) {

        var timeout, cache, rowcache, jq_results, val = '', e = this, options = $.extend({ 
            delay: 100,
            selector: null,
            stripeRows: null,
            loader: null,
            noResults: '',
            bind: 'keyup',
            onBefore: function () { 
                return;
            },
            onAfter: function () { 
                return;
            },
            show: function () {
                this.style.display = "";
            },
            hide: function () {
                this.style.display = "none";
            },
            prepareQuery: function (val) {
                return val.toLowerCase().split(' ');
            },
            testQuery: function (query, txt, _row) {
                for (var i = 0; i < query.length; i += 1) {
                    if (txt.indexOf(query[i]) === -1) {
                        return false;
                    }
                }
                return true;
            }
        }, opt);

        this.go = function () {

            var i = 0, 
            noresults = true, 
            query = options.prepareQuery(val),
            val_empty = (val.replace(' ', '').length === 0);

            for (var i = 0, len = rowcache.length; i < len; i++) {
                if (val_empty || options.testQuery(query, cache[i], rowcache[i])) {
                    options.show.apply(rowcache[i]);
                    noresults = false;
                } else {
                    options.hide.apply(rowcache[i]);
                }
            }

            if (noresults) {
                this.results(false);
            } else {
                this.results(true);
                this.stripe();
            }

            this.loader(false);
            options.onAfter();

            return this;
        };

        this.stripe = function () {

            if (typeof options.stripeRows === "object" && options.stripeRows !== null)
            {
                var joined = options.stripeRows.join(' ');
                var stripeRows_length = options.stripeRows.length;

                jq_results.not(':hidden').each(function (i) {
                    $(this).removeClass(joined).addClass(options.stripeRows[i % stripeRows_length]);
                });
            }

            return this;
        };

        this.strip_html = function (input) {
            var output = input.replace(new RegExp('<[^<]+\>', 'g'), "");
            output = $.trim(output.toLowerCase());
            return output;
        };

        this.results = function (bool) {
            if (typeof options.noResults === "string" && options.noResults !== "") {
                if (bool) {
                    $(options.noResults).hide();
                } else {
                    $(options.noResults).show();
                }
            }
            return this;
        };

        this.loader = function (bool) {
            if (typeof options.loader === "string" && options.loader !== "") {
                 (bool) ? $(options.loader).show() : $(options.loader).hide();
            }
            return this;
        };

        this.cache = function () {

            jq_results = $(target);

            if (typeof options.noResults === "string" && options.noResults !== "") {
                jq_results = jq_results.not(options.noResults);
            }

            var t = (typeof options.selector === "string") ? jq_results.find(options.selector) : $(target).not(options.noResults);
            cache = t.map(function () {
                return e.strip_html(this.innerHTML);
            });

            rowcache = jq_results.map(function () {
                return this;
            });

            return this.go();
        };

        this.trigger = function () {
            this.loader(true);
            options.onBefore();

            window.clearTimeout(timeout);
            timeout = window.setTimeout(function () {
                e.go();
            }, options.delay);

            return this;
        };

        this.cache();
        this.results(true);
        this.stripe();
        this.loader(false);

        return this.each(function () {
            $(this).bind(options.bind, function () {
                val = $(this).val();
                e.trigger();
            });
        });

    };

}(jQuery, this, document));

I try to figure out where and how I can make a split/add space between numbers and letters. Cause some people type for example "ip1500" and the script cant match the input with an element that is like "ip 1500". My problem ist that Im a js beginner.

I was trying and trying but i cant get it work. I also tried this

I found this spot and I think it can be done here where the everything get splitted by an " " (space):

prepareQuery: function (val) {
    return val.toLowerCase().split(' ');
    }, 

Would be very nice if somebody can help me.

Community
  • 1
  • 1
Kuba
  • 189
  • 3
  • 23

2 Answers2

6

If you want "123abc345def" to "123 abc 345 def". The replace function may help. The code is like this.

var str = "123abc345def";
str = str.replace(/(\d+)/g, function (_, num){
    console.log(num);
    return ' ' + num + ' ';
});
str = str.trim();
3

The code you linked didn't work mainly because it's using a different programming language to javascript. In theory, it should work, but javascript does not support regular expression lookbehinds (at this present time)..

Instead, I have re-wrote that fragment of code:

prepareQuery: function (val) {
function isNotLetter(a){
return (/[0-9-_ ]/.test(a));
}

var val=val.toLowerCase().split("");
var tempArray=val.join("").split("");
var currentIndex=1;

for (var i=0;i<val.length-1;i++){
if (isNotLetter(val[i]) !== isNotLetter(val[i+1])){
tempArray.splice(i+currentIndex, 0, " ");
currentIndex++;
}
}
return tempArray.join("");
}

Since you're new to javascript, I'm going to explain what it does.

  1. It declares a function in prepareQuery to check whether or not a string contains a letter [this can be moved somewhere else]
  2. It then splits val into an array and copies the content of val into tempArray
  3. An index is declared (explained later)
  4. A loop is made, which goes through every single character in val
  5. The if statement detects whether or not the current character (val[i] as set by the loop) is the same as the character next to it (val[i+1]).
  6. IF either one are different to the other (ie the current character is a letter while the next isn't) then a space is added to the tempArray at that "index"
  7. The index is incremented and used as an offset in #6
  8. The loop finishes, joins the "array" into a string and outputs the result.

DEMO: http://jsbin.com/ebitus/1/edit (JSFiddle was down....)

EDIT: Sorry, but I completely misinterpreted your question... You failed to mention that you were using "quicksearch" and jQuery. In that case I'm assuming that you have a list of elements that have names and you want to search through them with the plugin... A much easier way to match the user's query (if there is no space) is to strip the space from the search table along with the query itself - though original reverse method will work (just not as efficiently) [aka: expanding the user's query]

In this case, stripping the space from both the search table and user input would be a better method

    prepareQuery: function (val) {
        return val.toLowerCase().replace(/ /ig,'').split(" ");
    },
    testQuery: function (query, txt, _row) {
        txt=txt.toLowerCase().replace(/ /ig,'');
    for (var i = 0; i < query.length; i += 1) {
        if (txt.indexOf(query[i]) === -1) {
            return false;
        }
    }
    return true;

}

DEMO: http://jsfiddle.net/q9k9Y/3/

Edit 2:

It seems like your real intent is to create a fully functioning search feature on your website, not to just add spaces between letters and numbers. With this, I suggest using Quicksilver. I would love to work out an algorithm to extend quickSearcher but at the current time I cannot (timezones). Instead, I suggest using Quicksilver

http://jsbin.com/oruhet/12/

extramaster
  • 2,635
  • 2
  • 23
  • 28
  • Thank you very much, this works fine BUT now this splits every single letter and number. Exmaple: I type "pixma ip1500" and the script match even an element that is like this: "pixam pim 015" cause every single number and letter from the input is in the li element "pixam pim 015". In other words the li element contains every single number and letter from the input. Sorry for my bad english! – Kuba Nov 02 '12 at 10:20
  • Finaly I fixed the split problem for every single number or letter. I changed you last line "return tempArray.join("");" to "return tempArray.join("").split(' ');". So I just add this ".split(' ');" – Kuba Nov 02 '12 at 14:44
  • sorry, I was just editing my answer and I also realized this... However, I suggest a different approach, see edit.. BTW, if jsFiddle is down for you then please let me know, I'll put the code on jsbin if that happens. – extramaster Nov 02 '12 at 15:03
  • jsfiddle is down! Would be nice if you put your code on jsbin ;) – Kuba Nov 02 '12 at 15:24
  • Thanks. But this wont work cause you put in the table "pixma ip1500". But it musst be "pixma ip 1500" (with space). And when I now search for "pixma ip1500" it didnt match. ;) – Kuba Nov 02 '12 at 15:32
  • My mistake, I forgot to make it a global regular expression... http://jsbin.com/oruhet/4/edit I will edit my post accordingly; `replace(' ','')` is now `replace(/ /ig,'')` – extramaster Nov 02 '12 at 15:38
  • Nice but :D (sorry). Now you musst search in a exactly row. Example: I musst search for "pixma ip1500" to get a match. When i search for "pixma1500" or "pixma 1500" i didmnt get a match ;) – Kuba Nov 02 '12 at 15:45
  • I get it with you last code. Justed make from `return val.toLowerCase().replace(/ /ig,'').split(" ");` ==> `return val.toLowerCase().replace(/ /ig,' ').split(" ");` (add space after //ig,'SPACE'). I hope thats ok/legit?! – Kuba Nov 02 '12 at 15:58
  • Hi, I fully understand your real intent now, you want to create a fully functioning search in javascript, with this, I think that quickSearch is too primitive for the task you want it to do... Check my edit – extramaster Nov 02 '12 at 16:17
  • Hey, thank you very much for your time :) I try tomorrow quicksilver. When you are some day have enough time i would love to see you work out an algorithm to extend quickSearcher ;). But anyway. You helped me so much. Lot of thumbs up and a big thank you! – Kuba Nov 02 '12 at 16:25