16

In MySQL I use the like clause:

LIKE %some keyword% 

to perform searches on database records. What can I use to similarly do a search in a JavaScript? So if a user enters something like

ger

it will show

german shepard

Can't use:

str.search('ger');

since it seems to only match whole words

8 Answers8

40

it's not exact same as %LIKE% but you can use indexOf().

var str = "Mohsen",
    st = "Moh";

if(str.indexOf(st) > -1) // true
Mohsen
  • 64,437
  • 34
  • 159
  • 186
8

I'm not sure exactly in what context you are using the like operator (e.g. a form field), but you probably want to take advantage of javascript's regular expression object.

A simple example (in your case, for a LIKE query), might look like this:

var regex = /.*ger.*/
var matchesRegex = regex.test(yourString);
if (matchesRegex) {
    //do something
}

Alternatively, you can search for the incidence of your string using the indexOf operation:

var matches = yourString.indexOf("ger") >= 0 ? true : false;
if (matches) {
    //do something
}
NT3RP
  • 15,262
  • 9
  • 61
  • 97
  • 3
    it might be easy to mess up the regex given certain input – Nick Rolando Sep 30 '11 at 21:01
  • @Shredder: You're right. I don't know why it was the first solution that came to mind. At the same time a regex could allow other things similar to SQL syntax that you can't do with `indexOf` or other string operations. – NT3RP Sep 30 '11 at 21:03
  • I think the regex is promising, you just need to properly escape the dynamic input! [see post](https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex) – Richard Tyler Miles Jul 29 '22 at 16:34
4

search function does not only return whole words. Maybe you are getting confused by the fact it returns zero-based index, so...

// this returns 0 as positive match at position 0
"german shepherd".search('ger')

// this returns -1 as negative match
"german shepherd".search('gerx')

So you need to do comparison of result of search against -1 to see if it is a match or not - you can not just check for true/false.

So you could do...

if(str.search('ger') !== -1){
    // matches string
} else {
    // does not match string
}

// or another way
// add one to convert result to one-based index, and check truthiness
if(str.search('ger')+1){
    // there is a match
} else {
    // there is not a match
}
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
3

Assuming you've got a bunch of records as an array of strings you can use the JavaScript built-in Array.filter method:

var ss = ['german shepard', 'labrador', 'chihuahua'];
var matches = ss.filter(function(s) {
  return s.match(/ger/);
});
matches; //output => ['german shepard']

Or if your target JavaScript doesn't implement that method (e.g. it implements ECMAScript prior to 5th edition), then you can do a simple array search, e.g:

var searchArray = function(arr, regex) {
  var matches=[], i;
  for (i=0; i<arr.length; i++) {
    if (arr[i].match(regex)) matches.push(arr[i]);
  }
  return matches;
};
searchArray(ss, /h/); //output => ['german shepard', 'chihuahua']
Kishan Chauhan
  • 1,216
  • 1
  • 12
  • 19
maerics
  • 151,642
  • 46
  • 269
  • 291
1

I assume you have data came from database let say it is like

let names = ['yusuf', 'sabri', 'bayrakdar'];

You should use includes within a filter:

let searchValue = 'usu'
let filteredNames = names.filter(name => name.includes(searchValue));

filteredNames is going to be ["yusuf"]

yusuf_sabri
  • 129
  • 6
0

Here is an easy way to do it in JQuery.

This uses a filtering of text data inside of a table via a data-filter on the table row, but it can easily be used for other purposes.

$('#search').on('keyup', function() {
    var val = $.trim(this.value);
    if (val) {
        $('tr[data-filter!=' + val + ']').hide();
        $('tr[data-filter^=' + val + ']').show();
    } else {
       $('tr[data-filter]').show();
    }
});

In this example it will hide all table rows where an exact match wasn't found, and then filter by the start of the string value. The trim() function is useful in case all that's there is empty spaces, then it will still display everything as if a search was never made. If you want it to display the searched input where it's anywhere on the string, use a * instead of a ^. Both special characters are case sensitive. Also be sure that the hide command displays first and that both are present, or it won't work properly.

See another example here that utilizes both the ^ and * characters: http://jsfiddle.net/heatwaveo8/2VKae/

Ryan
  • 96
  • 1
  • 2
0

my code:

// file name 1 = "E_000096_01.jpg"
// file name 2 = "E_000096_02.jpg"
// file name 3 = "E_000096_03.jpg"
// file name 4 = "E_000095_01.jpg"
var code = "000096";
var files = fs.readdirSync(dir).filter(file => file.indexOf(code) >= 0 ? true : false)
// result
console.log(files)
//["E_000096_01.jpg","E_000096_02.jpg","E_000096_03.jpg"]
  • Posts should be in english only - https://meta.stackexchange.com/questions/13676/do-posts-have-to-be-in-english-on-stack-exchange – GrafiCode Nov 07 '18 at 17:06
0

I'm not sure if all browsers support all of these methods: http://www.javascriptkit.com/jsref/string.shtml

But it looks like there's a String.match() method that'll do what you want.

Mohsen
  • 64,437
  • 34
  • 159
  • 186
Erik
  • 1,674
  • 3
  • 15
  • 18