javascript – Find words with at least one capital letter

Question:

How can I get a list with the words that contain at least one capital letter in a string, without repeating?

In my attempt, it only gives me the last word of the chain as a result, that is: You.

function Calculate()
{
    var str = "JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. JavaScript is easy to learn. You will enjoy it.";
    var res = "";

    var newAr = str.split(/[ .,]+/).filter(String);

    for(var i = 0; i < newAr.length; i++) {
        if(newAr[i].match(/[A-Z]/)) {
            var WordCapLetts = newAr[i];
        }
    }

    res += "<br>Palabras con al menos una letra mayuscula: " + WordCapLetts; 

    document.getElementById("result").innerHTML = res;
}

Answer:

You are crushing the value of the variable where you store the word with capital letters in each iteration.

function Calculate()
{
var str = "JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. JavaScript is easy to learn. You will enjoy it.";
var res = "<br>Palabras con al menos una letra mayuscula: ";

var newAr = str.split(/[ .,]+/).filter(String);

for(var i = 0; i < newAr.length; i++) {
    if(newAr[i].match(/[A-Z]/)) {
        res += newAr[i] + " "; 
    }
}



document.getElementById("result").innerHTML = res;
}

This would work. and if you want to improve it, you could store the words in an array, iterate over the array putting commas and not put it in the last element … There are many ways

EDIT: To be able to add the words without repeating I have used a list and I have been iterating. EDIT 2: Changed logic to concatenate uppercase words.

function Calculate()
{
var str = "JavaScript is used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more. JavaScript is easy to learn. You will enjoy it.";
var res = "<br>Palabras con al menos una letra mayuscula: ";

var newAr = str.split(/[ .,]+/).filter(String);

var lista = [];

for(var i = 0; i < newAr.length; i++) {
    if(newAr[i].match(/[A-Z]/) && !lista.includes(newAr[i])) {
        lista.push(newAr[i]); 
    }
}

res+=lista.join(", ");


document.getElementById("result").innerHTML = res;
}
Scroll to Top