Brk
Brk

Reputation: 1297

How to catch all upper cases in javascript

I have a string like `"TransfCoolingFanG1" I want to have the output: "TCFG1". How I build a javascript function for this purpose?

Upvotes: 1

Views: 779

Answers (5)

Pranav C Balan
Pranav C Balan

Reputation: 115212

Use String#replace method and replace all small letters.

console.log(
  "TransfCoolingFanG1".replace(/[a-z]+/g, '')
)


UPDATE : If you want to remove all character except capital case or digit then use negated character class with regex.

console.log(
  "TransfCoolingFanG1".replace(/[^A-Z\d]+/g, '')
)

Upvotes: 1

John Smith
John Smith

Reputation: 11

EcmaScript 6 approach

inputString => inputString.split('').filter(x => x === x.toUpperCase()).join('')

So what happens here in this arrow function:

  1. Once we have inputString, we get an array of characters from it by applying function split with empty string '' separator
  2. Once we have array of characters, we want to find all uppercase letters.
  3. Apply filter function with an argument of predicate which tests each element of array for being uppercased or not. In case character does not equal it's uppercase variant, predicate returns false and filter erases element from array.
  4. Last step is just collecting new string from array of filtered characters by joining it with empty string '' separator

Upvotes: 1

Teshtek
Teshtek

Reputation: 1342

Maybe more native :

var yourString = "TransfCoolingFanG1";
var upString= "";
for (var i = 0; i < yourString.length;i++){
        if (isUpperCase(yourString.charAt(i)));{ 
            upString +=yourString.charAt(i);       
        }
 } 

window.alert(upString);

Upvotes: 1

Ayan
Ayan

Reputation: 8886

var str = "TransfCoolingFanG1";
var res = "";
var len = str.length;
for (var i = 0; i < len ; i++) 
    if (str[i] === str[i].toUpperCase()) 
      res = res + str[i];
window.alert(res);

Upvotes: 1

sinisake
sinisake

Reputation: 11318

Or, another approach (replace all EXCEPT uppercase letters and numbers):

str="TransfCo^^^oli*****ngFanG1";
str=str.replace(/[^A-Z0-9]/g,'');
console.log(str);

Upvotes: 2

Related Questions