Trim off '?' from strings in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>We are required to write a JavaScript function that takes in a string as the only argument. The string is likely to contain question marks (?) in the beginning and the end. The function should trim off all these question marks from the beginning and the end keeping everything else in place.</p><p><strong>For example &minus;</strong></p><p>If the input string is &minus;</p><pre class="prettyprint notranslate">const str = &#39;??this is a ? string?&#39;;</pre><p>Then the output should be &minus;</p><pre class="result notranslate">const output = &#39;this is a ? string&#39;;</pre><h2>Example</h2><p>Following is the code &minus;</p><pre class="prettyprint notranslate">const str = &#39;??this is a ? string?&#39;; const specialTrim = (str = &#39;&#39;, char = &#39;?&#39;) =&gt; { &nbsp; &nbsp;str = str.trim(); &nbsp; &nbsp;let countChars = orientation =&gt; { &nbsp; &nbsp; &nbsp; let inner = (orientation == &quot;left&quot;)? str : &nbsp; &nbsp; &nbsp; str.split(&quot;&quot;).reverse().join(&quot;&quot;); &nbsp; &nbsp; &nbsp; let count = 0; &nbsp; &nbsp; &nbsp; for (let i = 0, len = inner.length; i &lt; len; i++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (inner[i] !== char) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;count++; &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp; &nbsp; return (orientation == &quot;left&quot;)? count : (-count); &nbsp; &nbsp;}; &nbsp; &nbsp;const condition = typeof char === &#39;string&#39; &amp;&amp; str.indexOf(char) === 0 &amp;&amp; str.lastIndexOf(char, -1) === 0; &nbsp; &nbsp;if (condition) { &nbsp; &nbsp; &nbsp; str = str.slice(countChars(&quot;left&quot;), countChars(&quot;right&quot;)).trim(); &nbsp; &nbsp;}; &nbsp; &nbsp;return str; } console.log(specialTrim(str));</pre><h2>Output</h2><p>Following is the output on console &minus;</p><pre class="result notranslate">this is a ? string</pre>
raja
Updated on 10-Dec-2020 08:27:01

Advertisements