Thursday 2 November 2017

How to check whether a string contains a substring in JavaScript?





Usually I would expect a String.contains()
method, but there doesn't seem to be one.



What
is a reasonable way to check for this?


class="post-text" itemprop="text">
class="normal">Answer





ECMAScript 6 introduced href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes"
rel="noreferrer">String.prototype.includes:



class="snippet" data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">var string =
"foo",
substring =
"oo";

console.log(string.includes(substring));






includes
doesn’t
have Internet Explorer support
, though. In ECMAScript 5 or older environments,
use href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf"
rel="noreferrer">String.prototype.indexOf, which
returns -1 when a substring cannot be found:



class="snippet" data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">var string =
"foo",
substring =
"oo";

console.log(string.indexOf(substring) !==
-1);






No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...