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

Recombine characters of a string in JavaScript

PHPz
Release: 2023-09-16 21:41:02
forward
1021 people have browsed it

在 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';
Copy after login

output

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

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));
Copy after login

Output

[ &#39;thisisSme&#39;, &#39;123&#39;, &#39;! @&#39; ]
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template