-1

I need your help,

Using javascript, how can you find out if a match is in a string?

var x = "APPLE-PEAR/BANANA and ORANGE & LEMON"

So I need a function that would allow me to check value y against value x.

the value to search for:

y = "PEAR"

if (y matches the string in x) then return true
BobbyJones
  • 1,331
  • 1
  • 26
  • 44
  • 2
    Have you tried anything? I mean, JavaScript does have an [`includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) method... – Heretic Monkey Sep 30 '16 at 19:13
  • @MikeMcCaughan, [`.includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) is currently a bad recommendation. It was relatively recently added to JavaScript and has [limited/no support in older browsers (e.g. IE, Opera)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Browser_compatibility). In a few/several years it will be good to use. For now [`.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) would be a better recommendation. – Makyen Sep 30 '16 at 19:22
  • @Makyen. It's a comment, not an answer. Also, that browser support link is outdated. See [this list](http://kangax.github.io/compat-table/es6/#test-String.prototype_methods_String.prototype.includes) for a more updated list. That said, my comment was mostly about having the OP try something before asking, but since they've now been awarded for their lack of research with an answer, it's a bit moot. – Heretic Monkey Sep 30 '16 at 19:41
  • @MikeMcCaughan, I understand about the lack of research/own attempt issue on the part of the OP. Only thing we can do is vote down & vote/flag to close as duplicate (both are appropriate here with such an obvious lack of research). The link you provided shows IE11 as requiring a polyfill/external compiler, not as actually supported. `includes()` is not supported in the current version of IE11 (just tested to verify). – Makyen Sep 30 '16 at 20:02

2 Answers2

0
var x = "APPLE-PEAR/BANANA and ORANGE & LEMON"
y = "PEAR"
// Checks if string x having string y
if(x.includes(y)) { console.log("MATCH FOUND"); return true; }
// Returns index of string y in x , -1 if not present
if(x.indexOf(y) > -1) { console.log("MATCH FOUND"); return true; }

There are many ways of doing this. Please read the documentation for Javascript String object

nikjohn
  • 20,026
  • 14
  • 50
  • 86
0

Use String#indexOf

The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

var x = "APPLE-PEAR/BANANA and ORANGE & LEMON",
  y = "PEAR";
console.log(x.indexOf(y) !== -1); //If true, exist
Rayon
  • 36,219
  • 4
  • 49
  • 76