Spliting string with integers and charcters into two subarrays

时间:2018-02-22 04:30:46

标签: javascript regex

I have a string ,

var a ="abc3bv5";

i have to split this string into two arrays one array should contain all the integers in the string and one should contain the characters present in the string.

3 个答案:

答案 0 :(得分:1)

您可以拆分字符串,然后过滤所需的字符串:



var a = "abc3bv5";
var spl = a.split('');
var letters = spl.filter(char => /[a-z]/i.test(char));
var numbers = spl.filter(char => /[0-9]/.test(char));

console.log(letters);
console.log(numbers);

// or better
var result = {
  numbers: [],
  letters: []
};

spl.forEach(char => {
  if (/[a-z]/i.test(char)) {
    result.letters.push(char);
  } else if (/[0-9]/.test(char)) {
    result.numbers.push(char);
  }
});

console.log(result);




答案 1 :(得分:1)

检查以下代码。我希望它会有所帮助 -

var a ="abc3bv5";
var num = [];
var str = [];
for(var i = 0; i<a.length; i++){
  if (!isNaN(parseInt(a[i]))){
      num.push(a[i]);
   } else {
      str.push(a[i]);
   }
}

console.log(num);
console.log(str);

答案 2 :(得分:0)

对于函数/不可变方法:

$init = 150630;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;

echo "$hours:$minutes:$seconds";