- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Trying to get number for each character in string - JavaScript
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.
For example,
a = 1 b = 2 c = 3 d = 4 e = 5 . . . Y = 25 Z = 26
Therefore, if the input is "hello man",
Then the output should be a number for each character −
"8,5,12,12,15,13,1,14"
Example
Following is the code −
const str = 'hello man'; const charPosition = str => { str = str.split(''); const arr = []; const alpha = /^[A-Za-z]+$/; for(i=0; i < str.length; i++){ if(str[i].match(alpha)){ const num = str[i].charCodeAt(0) - 96; arr.push(num); }else{ continue; }; }; return arr.toString(); } console.log(charPosition(str));
Output
This will produce the following output in console −
"8,5,12,12,15,13,1,14"
- Related Articles
- Repeating each character number of times their one based index in a string using JavaScript
- Count number of occurrences for each char in a string with JavaScript?
- How to get a part of string after a specified character in JavaScript?
- Create palindrome by changing each character to neighboring character in JavaScript
- Turn each character into its ASCII character code and join them together to create a number in JavaScript
- How to get a string representation of a number in JavaScript?
- How to get a number value of a string in Javascript?
- Frequency of each character in String in Python
- Constructing a string based on character matrix and number array in JavaScript
- Java program to check occurence of each character in String
- Java program to check occurrence of each character in String
- How to count the number of occurrences of a character in a string in JavaScript?
- How to get a number of vowels in a string in JavaScript?
- Python program to find occurrence to each character in given string
- C# program to get max occurred character in a String

Advertisements