JavaScript Check whether string1 ends with strings2 or not

JavascriptWeb DevelopmentObject Oriented Programming

<p>We are required to write a JavaScript function that takes in two strings, say, string1 and string2 and determines whether the string1 ends with string2 or not.</p><p>For example &minus;</p><pre class="result notranslate">&quot;The game is on&quot; Here, &quot;on&quot; should return true</pre><p>While,</p><pre class="result notranslate">&quot;the game is off&quot; Above, &ldquo;of&quot; should return false</pre><p>Let&#39;s write the code for this function &minus;</p><h2>Example</h2><pre class="prettyprint notranslate">const first = &#39;The game is on&#39;; const second = &#39; on&#39;; const endsWith = (first, second) =&gt; { &nbsp; &nbsp;const { length } = second; &nbsp; &nbsp;const { length: l } = first; &nbsp; &nbsp;const sub = first.substr(l - length, length); &nbsp; &nbsp;return sub === second; }; console.log(endsWith(first, second)); console.log(endsWith(first, &#39; off&#39;));</pre><h2>Output</h2><p>The output in the console will be &minus;</p><pre class="result notranslate">true false</pre>
Updated on 31-Aug-2020 07:00:38