How do I find the position of all uppercase characters in a string?

How to get the positions of all top characters in a string, in jquery?

Suppose var str = "thisIsAString";

the answer will be 4,6,7 (for t with index = 0)

+3


source to share


4 answers


Loop over letters and match them with regex. for example



var inputString = "What have YOU tried?";
var positions = [];
for(var i=0; i<inputString.length; i++){
    if(inputString[i].match(/[A-Z]/) != null){
        positions.push(i);
    }
}
alert(positions);

      

+11


source


You probably want to use a regular expression to match the matching characters (in this case [A-Z]

or similar) and iterate over the matches. Something like:

// Log results to the list
var list = document.getElementById("results");
function log(msg) {
  var item = document.createElement("li");
  item.innerHTML = msg;
  list.appendChild(item);
}

// For an input, match all uppercase characters
var rex = /[A-Z]/g;
var str = "abCdeFghIjkLmnOpqRstUvwXyZ";
var match;
while ((match = rex.exec(str)) !== null) {
  log("Found " + match[0] + " at " + match.index);
}
      

<ol id="results"></ol>
      

Run codeHide result




This will loop over the string, matching each uppercase character and (in the example) adding it to the list. You can just as easily add it to an array or use it as an input to a function.

This is the same method as shown in the MDN example for RegExp.exec

, and some additional details are provided in the matches. You can also use more complex regular expressions and this method should still work.

+1


source


Just use the cam match()

. Example:

var str = 'thisIsAString';
var matches = str.match(/[A-Z]/g);
console.log(matches);

      

+1


source


Pseudocode (not much time)

var locations = [];
function getUpperLocs(var text = ''){
    for(var i = 0;i == check.length();i++)
{
    if(checkUpper(text){
        locations.push(i)
    }
} 

    function checkUppercase(var str = '') {
        return str === str.toUpper();
    }
}

      

allright no to many pseodocode, but probably some syntax errors.

0


source







All Articles