Question 1: If the string is 'as2378dj1sad2', the front end separates the previous letters from the subsequent numbers, and the results are placed in the array in the order of the strings

Question 1: If the string is 'as2378dj1sad2', the front end separates the previous letters from the subsequent numbers, and the results are placed in the array in the order of the strings

Answer: You can use JavaScriptregular expressions to separate letters and numbers in a string, and store the results in an array in string order. Here is a code example:

const s = 'as2378dj1sad2';
const result = [];
let letters = '';
let numbers = '';

for (let i = 0; i < s.length; i++) {
    
    
  if (/[a-zA-Z]/.test(s[i])) {
    
      // 如果是字母
    if (numbers !== '') {
    
      // 如果之前有数字
      result.push(numbers);  // 将数字存入结果数组
      numbers = '';  // 重置数字
    }
    letters += s[i];  // 将字母添加到字母字符串中
  } else if (/\d/.test(s[i])) {
    
      // 如果是数字
    if (letters !== '') {
    
      // 如果之前有字母
      result.push(letters);  // 将字母存入结果数组
      letters = '';  // 重置字母
    }
    numbers += s[i];  // 将数字添加到数字字符串中
  }
}

// 处理最后一个字母或数字
if (letters !== '') {
    
    
  result.push(letters);
} else if (numbers !== '') {
    
    
  result.push(numbers);
}

console.log(result);  // 输出 ["as", "2378", "dj", "1", "sad", "2"]

First, we define a string s, which contains letters and numbers. Then, we define an empty array resultto store the separated results. Next, we use a loop to iterate over seach character in the string. If the current character is a letter, it is added to the alphabetic string letters; if the current character is a number, it is added to the numeric string numbers. If the next character is a letter, store the current string of numbers in numbersthe result array resultand reset numbersthe string; if the next character is a number, store the current string of letters in lettersthe result array resultand reset lettersthe character string. Finally, we process the last letter or number and store it resultin the resulting array. Finally, we print out resultthe array.

Guess you like

Origin blog.csdn.net/weixin_55846296/article/details/130013502
Recommended