Home  >  Article  >  Web Front-end  >  Recombine characters of a string in JavaScript

Recombine characters of a string in JavaScript

PHPz
PHPzforward
2023-09-16 21:41:02996browse

在 JavaScript 中重新组合字符串的字符

Question

We need to write a JavaScript function that takes a string str as the first and only parameter.

String str can contain three types of characters -

  • English letters: (A-Z), (a-z)

  • Numbers: 0-9

  • Special characters - all other remaining characters

Our function should iterate over the string and construct a string containing the following Array of contents: exactly three elements, the first contains all letters present in the string, the second contains numbers and the third special characters maintains the relative order of characters. We should eventually return this array.

For example, if the input to the function is

input

const str = 'thi!1s is S@me23';

output

const output = [ 'thisisSme', '123', '! @' ];

example

The following is the code-

Real-time demonstration

const str = 'thi!1s is S@me23';
const regroupString = (str = '') => {
   const res = ['', '', ''];
   const alpha = 'abcdefghijklmnopqrstuvwxyz';
   const numerals = '0123456789';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(alpha.includes(el) || alpha.includes(el.toLowerCase())){
         res[0] += el;
         continue;
      };
      if(numerals.includes(el)){
         res[1] += el;
         continue;
      };
      res[2] += el;
   };
   return res;
};
console.log(regroupString(str));

Output

[ &#39;thisisSme&#39;, &#39;123&#39;, &#39;! @&#39; ]

The above is the detailed content of Recombine characters of a string in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete