Home > database >  how to filter the elements based on data type in given list
how to filter the elements based on data type in given list

Time:04-09

filterString('str$$$1232text%<>');

The answer should be like

a = 'strtext' b = '$$$%<>'enter code here c = '1231'

CodePudding user response:

Going by your question, assuming it to be in string, two possible ways are checking by regex or Unicode.

word = 'str$$$1232text%<>'
console.log(filterStringByUnicode(word))
console.log(filterStringByRegex(word)) 

function filterStringByRegex(word){
let str = num = spl = '';
  [...word].forEach(el => {
    if(el.match(/[a-z]/))
      str  = el;
    else if(el.match(/[0-9]/))
      num  = el;
    else
      spl  = el;
  })
  return {a:str,b:spl,c:num}
}

function filterStringByUnicode(word){
  let str = num = spl = '';
  [...word].forEach(el => {
    let unicode = el.charCodeAt(0)
    if(unicode >= 91 && unicode <= 122) //Unicode for a-z
      str  = el;
    else if(unicode >= 48 && unicode <= 57) //Unicode for numbers
      num  = el;
    else //rest
      spl  = el;
  })
  return {a:str,b:spl,c:num}
}

CodePudding user response:

Your question seems not to be about filters but about how to split a string into substrings following some rules. I suggest you to look around RegExp(theRule) in JS.

A solution could be similar to :

var aString = 'str$$$1232text%<>';
var a=''; var b=''; var c='';
var regexA = new RegExp('[a-z]'); // lowercase a to z
var regexB = new RegExp('$%<>'); // only this special chars but you can add more
var regexC = new RegExp('[0-9]'); // 0 to 9
for(const aCharacter of aString.split('')){ // split will make an Array of chars
    if (regexA.test(aCharacter) // the 'test' method return true if the char respect the regex rule
        a = a.concat(aCharacter);
    if (regexB.test(aCharacter)
        b = b.concat(aCharacter);
    if (regexC.test(aCharacter)
        c = c.concat(aCharacter);
}
  • Related