How to search for a string in JavaScript?

JavascriptWeb DevelopmentFront End Technology

<p style="">Following is the code for searching a string in JavaScript &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/RYmpsXwX" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot; &gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt; &lt;title&gt;Document&lt;/title&gt; &lt;style&gt; &nbsp; &nbsp;body { &nbsp; &nbsp; &nbsp; font-family: &quot;Segoe UI&quot;, Tahoma, Geneva, Verdana, sans-serif; &nbsp; &nbsp;} &nbsp; &nbsp;.result { &nbsp; &nbsp; &nbsp; font-size: 20px; &nbsp; &nbsp; &nbsp; font-weight: 500; &nbsp; &nbsp;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Searching a string in JavaScript&lt;/h1&gt; &lt;div class=&quot;sample&quot;&gt;The spring season is about to come.&lt;/div&gt; &lt;div style=&quot;color: green;&quot; class=&quot;result&quot;&gt;&lt;/div&gt; &lt;button class=&quot;btn&quot;&gt;CLICK HERE&lt;/button&gt; &lt;h3&gt; Click on the above button to find the string &#39;spring&#39; in the above string &lt;/h3&gt; &lt;script&gt; &nbsp; &nbsp;let btnEle = document.querySelector(&quot;.btn&quot;); &nbsp; &nbsp;let sampleEle = document.querySelector(&quot;.sample&quot;).innerHTML; &nbsp; &nbsp;let resEle = document.querySelector(&quot;.result&quot;); &nbsp; &nbsp;btnEle.addEventListener(&quot;click&quot;, () =&gt; { &nbsp; &nbsp; &nbsp; resEle.innerHTML = &quot;The string spring is found at position &quot; + sampleEle.search(&quot;spring&quot;); &nbsp; &nbsp;}); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</pre><h2>Output</h2><p>The above code will produce the following output &minus;</p><p style=""><img src="https://www.tutorialspoint.com/assets/questions/media/39998/search_string.jpg" class="fr-fic fr-dib" width="600" height="197"></p><p>On clicking the &lsquo;CLICK HERE&rsquo; button &minus;</p><p style=""><img src="https://www.tutorialspoint.com/assets/questions/media/39998/search_string1.jpg" class="fr-fic fr-dib" width="600" height="188"></p>
raja
Updated on 15-Jul-2020 13:25:44

Advertisements