How to pick only Capital characters from the string? - javascript

I am try to pick capital characters from the string with the help of a function and for loop but i can't figure out how i can do it i try using toUpperCase as you see it in the code but it is not work any idea how i can do it ?
function onlyCapitalLetters(cap){
var string = "";
for(var i = 0; i < cap.length; i++){
if(cap[i] === cap.toUpperCase()){
string += cap[i];
}
}
return string;
}
onlyCapitalLetters("Apple");

You can try the regex, with String.prototype.match to return capital letters only:
function onlyCapitalLetters(cap){
return cap.match(/[A-Z]/g, "").join(''); // join the array to return a string
}
console.log(onlyCapitalLetters("Apple"));
console.log(onlyCapitalLetters("BUTTerfly"));
console.log(onlyCapitalLetters("LION"));

Can you try like this
function findUpcase(value){
input = value
data = ""
input.split("").map(res => {
if(res == res.toUpperCase()){
data = data+ res
}
})
return data
}
console.log( findUpcase("MyNameIsVelu") );
//'MNIV'

As noted in comments you need to change cap.toUpperCase() to cap[i].toUpperCase().
But you can do it with just one replace:
console.log('Apple Orange'.replace(/[^A-Z]/g, ""));

It is possible to use replace method with Regex to eliminate numbers and letters written in lowercase:
let str = 'T1eeeEeeeSssssssTttttt';
let upperCase = str.replace(/[a-z0-1]/g, '')
console.log(upperCase);

Please Use Below code to get Capital letter of the sentence :
Demo Code
var str = 'i am a Web developer Student';
var sL = str.length;
var i = 0;
for (; i < sL; i++) {
if (str.charAt(i) != " ") {
if (str.charAt(i) === str.charAt(i).toUpperCase()){
console.log(str.charAt(i));
break;
}
}
}

Related

Palindrome Checker need a hand

I'm working on freeCodeCamp's Palindrome Checker. My code is a bit messy but it pretty works on every test except the nineth one. palindrome("almostomla") should return false but in my code it returns trueinstead. I think my nineth code has a little problem but couldn't solve that. I wonder where am I missing something.
function palindrome(str) {
let str1 = str.replace(/[^a-zA-Z\d:]/gi, '');
let str2 = str1.replace(/,/gi, '');
let str3 = str2.replace(/\./gi, '');
let str4 = str3.replace(/_/, "-");
let myStr = str4.toLowerCase(); //My string is ready for play
for (let i = 0; i < myStr.length; i++) {
if (myStr[i] != myStr[myStr.length - (i+1)]) { //I think there is a little mistake on this line
return false;
} else {
return true;
}
}
The problem is that you're only checking the first and last characters of the string. You should return true only after all iterations have finished:
function palindrome(str) {
let str1 = str.replace(/[^a-zA-Z\d:]/gi, '');
let str2 = str1.replace(/,/gi, '');
let str3 = str2.replace(/\./gi, '');
let str4 = str3.replace(/_/, "-");
let myStr = str4.toLowerCase(); //My string is ready for play
for (let i = 0; i < myStr.length; i++) {
if (myStr[i] != myStr[myStr.length - (i + 1)]) {
return false;
}
}
return true;
}
console.log(palindrome("almostomla"));
console.log(palindrome("foof"));
console.log(palindrome("fobof"));
console.log(palindrome("fobbf"));
Note that your initial regular expression is sufficient - it removes all characters that aren't alphabetical, numeric, or :, so the other 3 regular expressions you run later are superfluous. Since you're using the i flag, you can also remove the A-Z from the regex:
const stringToTest = str.replace(/[^a-z\d:]/gi, '');
It would also probably be easier just to .reverse() the string:
function palindrome(str) {
const strToTest = str.replace(/[^a-z\d:]/gi, '');
return strToTest.split('').reverse().join('') === strToTest;
}
console.log(palindrome("almostomla"));
console.log(palindrome("foof"));
console.log(palindrome("fobof"));
console.log(palindrome("fobbf"));

Write a function that returns a new string containing all matches. Each match is then replaced by replacement characters

Write a function that returns a new string containing all matches. Each match is then replaced by replacement characters.I cannot used built-in function ex:replace,split,splice...
Hi guys can you help me with this.I am new to this and i am sorry that the code didn't make sense.Thanks
function func4(str,chartoChange,chartoReplace){
var result = "";
for (var i=0;i<str.length;i++){
var x = str.charAt(i);
if (x==chartoChange){
// How to replace with chartoReplace
}
result += str
}
return result
}
Example (("abc","a","X") return Xbc
Concatenate either the chartoReplace or the original str[i] with result, depending on whether str[i] === chartoChange:
function func4(str, chartoChange, chartoReplace) {
var result = "";
for (var i = 0; i < str.length; i++) {
result += str[i] === chartoChange
? chartoReplace
: str[i];
}
return result
}
console.log(func4("abc", "a", "X")) // return Xbc
Just use a regex and replace:
function func4(str, charToChange, charToReplace) {
return str.replace(new RegExp(charToChange, "g"), charToReplace);
}
console.log(func4("abc", "a", "X"));
console.log(func4("Hello World", "l", "q"));

How can I write a function that will format a camel cased string to have spaces?

I need to write a function that will take a string 'camelCased' and then format it to add spaces to it: 'camel Cased'.
You can use regex to split on capitals and then rejoin with space:
.split(/(?=[A-Z])/).join(' ')
let myStrings = ['myString','myTestString'];
function myFormat(string){
return string.split(/(?=[A-Z])/).join(' ');
}
console.log(myFormat(myStrings[0]));
console.log(myFormat(myStrings[1]));
You could replace upper case letters with a leading space.
var string = 'camelCased';
console.log(string.replace(/[A-Z]/g, ' $&'));
I think this will Help
function replaceCamelCase()
{
var op="";
for(int i = 0; i < input.Length; i++)
{
if(isUpper(input.charAt(i))
{
op+=" "+input.charAt(i);
}
op+=input.charAt(i);
}
alert(op);
}
function isUpper(){
if (character == character.toUpperCase())
{
return true;
}
return false;
}

How to apply special characters in string?

Suppose we have the following string object:
var str = "Real\bWorl\bd";
considering \b as BackSpace character, I want a mechanism to get
ReaWord
as result, this means BackSpace character some how compiled within the string.
aside from BackSpace, this special character might be Delete.
Thanks in advance....
try this
function replaceBackslash(str)
{
return str.split(/[a-z]\b/).join("")+ str.charAt(str.length -1);
}
replaceBackslash( "Real\bWorld\bddd" );
replaceBackslash( "Real\bWorld" );
function formatStr(str){
if(str.indexOf("\b")!=-1){
return formatStr(str.substring(0, str.indexOf("\b")-1) +
str.substring(str.indexOf("\b")+1, str.length));
}
else return str;
}
var str = "Real\bWor\bld";
alert(formatStr(str));
Check this
function removeBackspaces()
{
var str = "Real\bWorl\bd";
var word = "";
for(var i=0; i < str.length; i++)
{
if(str[i] != '\b')
{
word += str[i]
}
else
{
//var lastIndex = word.lastIndexOf(" ");
word = word.substring(0, word.length-1);
}
}
return word;
}
use following code
unescape(str)

Javascript Split string on UpperCase Characters

How do you split a string into an array in JavaScript by Uppercase character?
So I wish to split:
'ThisIsTheStringToSplit'
into
['This', 'Is', 'The', 'String', 'To', 'Split']
I would do this with .match() like this:
'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+/g);
it will make an array like this:
['This', 'Is', 'The', 'String', 'To', 'Split']
edit: since the string.split() method also supports regex it can be achieved like this
'ThisIsTheStringToSplit'.split(/(?=[A-Z])/); // positive lookahead to keep the capital letters
that will also solve the problem from the comment:
"thisIsATrickyOne".split(/(?=[A-Z])/);
.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")
This should handle the numbers as well.. the join at the end results in concatenating all the array items to a sentence if that's what you looking for
'ThisIsTheStringToSplit'.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")
Output
"This Is The String To Split"
Here you are :)
var arr = UpperCaseArray("ThisIsTheStringToSplit");
function UpperCaseArray(input) {
var result = input.replace(/([A-Z]+)/g, ",$1").replace(/^,/, "");
return result.split(",");
}
This is my solution which is fast, cross-platform, not encoding dependent, and can be written in any language easily without dependencies.
var s1 = "ThisЭтотΨόυτÜimunəՕրինակPříkladדוגמאΠαράδειγμαÉlda";
s2 = s1.toLowerCase();
result="";
for(i=0; i<s1.length; i++)
{
if(s1[i]!==s2[i]) result = result +' ' +s1[i];
else result = result + s2[i];
}
result.split(' ');
Here's an answer that handles numbers, fully lowercase parts, and multiple uppercase letters after eachother as well:
const wordRegex = /[A-Z]?[a-z]+|[0-9]+|[A-Z]+(?![a-z])/g;
const string = 'thisIsTHEString1234toSplit';
const result = string.match(wordRegex);
console.log(result)
I'm a newbie in programming and this was my way to solve it, using just basics of JavaScript declaring variables as clean for someone reading as possible, please don't kill me if it is not optimized at all, just starting with coding hehe :)
function solution(string) {
let newStr = '';
for( i = 0; i < string.length ; i++ ) {
const strOriginal = string[i];
const strUpperCase = string[i].toUpperCase();
if( strOriginal === strUpperCase) {
newStr = newStr + ' ' + strOriginal;
} else {
newStr = newStr + strOriginal;
}
}
return console.log(newStr);
}
solution('camelCasing');
string DemoStirng = "ThisIsTheStringToSplit";
for (int i = 0; i < DemoStirng.Length; i++) {
if (i != 0)
{
if ((int)DemoStirng[i] <= 90 && (int)DemoStirng[i] >= 65)
{
var aStringBuilder = new StringBuilder(DemoStirng);
aStringBuilder.Insert(i, ",");
DemoStirng = aStringBuilder.ToString();
i++;
}
}
}
string[] words = DemoStirng.Split(',');

Categories

Resources