How to test a regex match to a single character?

129
May 01, 2019, at 05:40 AM

I am attempting to test a regex against a single character within a string using the following code:

I've attempted to do this using the String.prototype.match method as well as with the RegEx.test method, to no avail.

An example of an input would be "HELLO124". I want the console to log with every uppercase letter, but not with anything else.

function rot13(str) { 
  let regex = /[A-Z]/; 
  for (let i = 0; i < str.length; i++) { 
    if (regex.test(str[i])) { 
      console.log('Match!'); 
    } 
  } 
} 
rot13('HELLO124');

I am never reaching the 'Match!' output.

Answer 1

As commented by p.s.w.g, the regex /[A-Z]/ matches only uppercase letters.

To match any letter (I assume this is what you mean by "a single character"?), use /[A-Za-z]/, or /[A-Z]/i (i for case insensitive).

Edit: now that you clarified your problem, I tested your snippet, and it is working for me. Perhaps you are not passing the string correctly to the method.

Try console logging the string inside the method to make sure.

rot13("HELLO1234"); 
 
function rot13(str) { 
    let regex = /[A-Z]/;   
  for(let i = 0; i < str.length; i++){ 
      if(regex.test(str[i])){ 
          console.log('Match!'); 
      } 
  } 
}

Answer 2

For one upper case:

/[A-Z]{1}/g

For one lower case:

/[a-z]{1}/g

For one lower or upper case:

/[a-zA-Z]{1}/g

For one lower or upper case:

/[a-zA-Z]{1}/g

For one anychar (includes, everything basically) case:

 /.{1}/g

For one either lower, upper or number

/[a-zA-Z0-9]{1,1}/g

You can try your regexper HERE:) is a reaaaaally useful tool.

Rent Charter Buses Company
READ ALSO
How do you check if value exists within Firebase live database using Firebase Functions?

How do you check if value exists within Firebase live database using Firebase Functions?

I am trying to setup a live database through firebase and test if a random value exists within it using Firebase FunctionsAny help will be greatly appreciated

118
View Android webview network requests that occurred on page load in Chrome devtools

View Android webview network requests that occurred on page load in Chrome devtools

If you have a webview open in Android, you can inspect it in Chrome devtoolsHowever, I can't open the devtools first, then open the webview to log network requests that occur on page load

145
Express JS form validation with Joi gives an error

Express JS form validation with Joi gives an error

I'm new to Node and i have tried to validate a form with Joi moduleEverything seems to work but my code returns an error

137
Javascript, in a React application assign to {} in a function component, code review

Javascript, in a React application assign to {} in a function component, code review

I have this code in a friend of mine React application and I need to understand what this code does explicitly:

128