Trying to get number for each character in string - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

<p>We are required to write a JavaScript function that takes in a string. It should print out each number for every corresponding letter in the string.</p><p>For example,</p><pre class="result notranslate">a = 1 b = 2 c = 3 d = 4 e = 5 . . . Y = 25 Z = 26</pre><p>Therefore, if the input is &quot;hello man&quot;,</p><p>Then the output should be a number for each character &minus;</p><pre class="result notranslate">&quot;8,5,12,12,15,13,1,14&quot;</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;hello man&#39;; const charPosition = str =&gt; { &nbsp; &nbsp;str = str.split(&#39;&#39;); &nbsp; &nbsp;const arr = []; &nbsp; &nbsp;const alpha = /^[A-Za-z]+$/; &nbsp; &nbsp;for(i=0; i &lt; str.length; i++){ &nbsp; &nbsp; &nbsp; if(str[i].match(alpha)){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const num = str[i].charCodeAt(0) - 96; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;arr.push(num); &nbsp; &nbsp; &nbsp; }else{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;continue; &nbsp; &nbsp; &nbsp; }; &nbsp; &nbsp;}; &nbsp; &nbsp;return arr.toString(); } console.log(charPosition(str));</pre><h2>Output</h2><p>This will produce the following output in console &minus;</p><pre class="result notranslate">&quot;8,5,12,12,15,13,1,14&quot;</pre>
raja
Updated on 30-Sep-2020 14:34:18

Advertisements