How can I get a list of words that contain at least one uppercase letter in a string, without repeating?
In my attempt, it only gives me the result of the last word of the string, 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;
}
You're mashing up the value of the variable where you store the capitalized word on each iteration.
This would work. Now if you want to improve it you could store the words in an array, iterate over the array putting commas and in the last element don't put it... 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.
It depends what you define by " word ", and that has a lot to do with what a capital letter is. Are they English words with letters from
a
toz
? Are they Spanish words with accented vowels andñ
? Or in Chinese, without capital letters?Words with at least one capital letter . A word that has at least one uppercase is one that has any number of lowercase letters at the beginning, followed by an uppercase, followed by any number of letters. We can define the following regex:
Let's see the case for Spanish, better:
And here the result:
unique values . If you are also interested in filtering that there are no duplicates, we can build one
Set
(ES6, which only allows unique values) and return it to an array:or, in older browsers, seeing that it is the first index of each element:
Code:
A simple workaround that you do NOT use
regex
is to simply see if the letter matches "that same uppercase letter". For this we use the methodtoUpperCase
.You can also use the regular expression to get the words with at least one capital letter. The match() function returns an array of matches. And at the end we use the unique() function in that array so that it eliminates the repeated words. I leave you here an example.
It can be used
map()
to iterate through the array and check if each element has a capital letter.Then, to get the unique values, convert to a
Set
, and finally to an array using the spread operator like[...elSetGenerado]
.