How do I find the position of all uppercase characters in a string?
4 answers
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>
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 to share
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 to share