Return a splitted array of the string based on all the specified separators - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>We are required to write a JavaScript function that takes in a string and any number of characters specified as separators. Our function should return a splitted array of the string based on all the separators specified.</p><p>For example &minus;</p><p>If the string is &minus;</p><pre class="result notranslate">const str = &#39;rttt.trt/trfd/trtr,tr&#39;;</pre><p>And the separators are &minus;</p><pre class="result notranslate">const sep = [&#39;/&#39;, &#39;.&#39;, &#39;,&#39;];</pre><p>Then the output should be &minus;</p><pre class="result notranslate">const output = [ &#39;rttt&#39;, &#39;trt&#39;, &#39;trfd&#39;, &#39;trtr&#39; ];</pre><h2>Example</h2><p>Following is the code &minus;</p><!---<p><a href="" target="_blank" rel="nofollow" class="demo"><i class="fa-external-link"></i> Live Demo</a></p>---><pre class="prettyprint notranslate">const str = &#39;rttt.trt/trfd/trtr,tr&#39;; const splitMultiple = (str, ...separator) =&gt; { &nbsp; &nbsp;const res = []; &nbsp; &nbsp;let start = 0; &nbsp; &nbsp;for(let i = 0; i &lt; str.length; i++){ &nbsp; &nbsp; &nbsp; if(!separator.includes(str[i])){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;continue; &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; res.push(str.substring(start, i)); &nbsp; &nbsp; &nbsp; start = i+1; &nbsp; &nbsp;}; &nbsp; &nbsp;return res; }; console.log(splitMultiple(str, &#39;/&#39;, &#39;.&#39;, &#39;,&#39;))</pre><h2>Output</h2><p>This will produce the following output on console &minus;</p><pre class="result notranslate">[ &#39;rttt&#39;, &#39;trt&#39;, &#39;trfd&#39;, &#39;trtr&#39; ]</pre>
raja
Updated on 09-Nov-2020 11:03:56

Advertisements