I'm working on alternating the case of a string (for example asdfghjkl to AsDfGhJkL).
I tried to do this. I found some code that is supposed to do it, but it doesn't seem to be working.
var str="";
var txt=document.getElementById('input').value;
for (var i=0; i<txt.length; i+2){
str = str.concat(String.fromCharCode(txt.charCodeAt(i).toUpperCase()));
}
Here's a quick function to do it. It makes the entire string lowercase and then iterates through the string with a step of 2 to make every other character uppercase.
var alternateCase = function (s) {
var chars = s.toLowerCase().split("");
for (var i = 0; i < chars.length; i += 2) {
chars[i] = chars[i].toUpperCase();
}
return chars.join("");
};
var txt = "hello world";
console.log(alternateCase(txt));
HeLlO WoRlD
The reason it converts the string to an array is to make the individual characters easier to manipulate (i.e. no need for String.prototype.concat()).
Here an ES6 approach:
function swapCase(text) {
return text.split('').map((c,i) =>
i % 2 == 0 ? c.toLowerCase() : c.toUpperCase()
).join('');
}
console.log(swapCase("test"))
You should iterate the string and alternate between upper-casing the character and lower-casing it:
for (var i=0; i<txt.length; i++) {
var ch = String.fromCharCode(txt.charCodeAt(i);
if (i % 2 == 1) {
ch = ch.toUpperCase();
} else {
ch = ch.toLowerCase();
}
str = str.concat(ch);
}
Related
I'm working on a Racker Rank problem whose function in JavaScript receives a single parameter (input).
Input Format:
The first line contains an integer, (the number of test cases).
Each line of the subsequent lines contain a String.
I need to print the even-indexed and odd-indexed characters of each string (S) separated by a space on a single line (see the Sample below for more detail).
2
Hacker
Rank
Hce akr
Rn ak
Is there a way to read the input line-by-line and save each string in a specific variable? If I achieve that I know how to solve the problem by iterating through the string. Otherwise, I'm lost. If not, how else could I handle the input? Thanks!
Readline doesn't seem to be the way to go.
function processData(input) {
//Enter your code here
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
What I have tried without success:
function processData(input) {
let myArray = input.split("\n");
let even_indexed = "";
let odd_indexed = "";
for (let i = 1; i <= myArray.length; i++) {
let str = myArray[i];
let len = str.length;
for (let j = 0; j < len; j++){
if (j % 2 == 0) { //check if the index is even;
even_indexed.concat(str[j]);
}
else {
odd_indexed.concat(str[j]);
}
}
}
console.log("%s %s", even_indexed, odd_indexed);
}
Can't you just use split() method with a newline operator?
<script>
let x= `Hey
I'm
a
multiline
string`
console.log(x.split("\n"))
</script>
The result will be an array on which every element represents a line of your input.
I made this pretty quickly so I apologize for it being kinda messy and I know there are probably more efficient ways of doing this, but it does what you are asking for.
let input = `This
is
a
multiline
string`
let splitWords = [];
input.split(/\r?\n/).forEach(function(e){ // Split the array by \n (newline) and/or \r (carriage return)
currentLine = {evenIndex: [], oddIndex: []}
for(let i = 0; i < e.length; i++){
if((i + 1)%2 === 0){
currentLine.evenIndex.push(e[i]);
}
else{
currentLine.oddIndex.push(e[i]);
}
}
splitWords.push(currentLine);
});
splitWords.forEach(function(e){
console.log(e.oddIndex.join('') + " " + e.evenIndex.join(''))
});
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 1));
}
if (/[aeiou]/.test(str[i])) {
str = str.replace(str[i], alphabet.charAt(index + 26));
}
}
return str;
}
When I call LetterChanges("hello"), it returns 'Ifmmp' which is correct, but when "sent" is passed it returns 'ufOt' instead of 'tfOu'. Why is that?
str.replace() replaces the first occurrence of the match in the string with the replacement. LetterChanges("sent") does the following:
i = 0 : str.replace("s", "t"), now str = "tent"
i = 1 : str.replace("e", "f"), now str = "tfnt"
i = 2 : str.replace("n", "o"), now str = "tfot", then
str.replace("o", "O"), now str = "tfOt"
i = 3 : str.replace("t", "u"), now str = "ufOt"
return str
There are several issues. The main one is that you could inadvertently change the same letter several times.
Let's see what happens to the s in sent. You first change it to t. However, when it comes to changing the final letter, which is also t, you change the first letter again, this time from t to u.
Another, smaller, issue is the handling of the letter z.
Finally, your indexing in the second if is off by one: d becomes D and not E.
You can use String.replace to avoid that:
function LetterChanges(str) {
return str.replace(/[a-zA-Z]/g, function(c){
return String.fromCharCode(c.charCodeAt(0)+1);
}).replace(/[aeiou]/g, function(c){
return c.toUpperCase();
});
}
But there is still a bug: LetterChanges('Zebra') will return '[fcsb'. I assume that is not your intention. You will have to handle the shift.
Try this one:
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = '';
var temp;
for (var i = 0; i < str.length; i++) {
var index = alphabet.indexOf(str[i])
if (/[a-zA-Z]/.test(str[i])) {
//str = str.replace(str[i], alphabet.charAt(index + 1));
temp= alphabet.charAt(index + 1);
index = index+1;
}
else if(str[i] == ' '){
temp = ' ';
}
if (/[aeiou]/.test(temp)) {
temp = alphabet.charAt(index + 26);
}
result += temp;
}
return result;
}
var str = 'bcd12';
str = str.replace(/[a-z]/gi, function(char) { //call replace method
char = String.fromCharCode(char.charCodeAt(0)+1);//increment ascii code of char variable by 1 .FromCharCode() method will convert Unicode values into character
if (char=='{' || char=='[') char = 'a'; //if char values goes to "[" or"{" on incrementing by one as "[ ascii value is 91 just after Z" and "{ ascii value is 123 just after "z" so assign "a" to char variable..
if (/[aeiuo]/.test(char)) char = char.toUpperCase();//convert vowels to uppercase
return char;
});
console.log(str);
Check this code sample. There is no bug in it. Not pretty straight forward but Works like a charm. Cheers!
function LetterChanges(str) {
var temp = str;
var tempArr = temp.split("");//Split the input to convert it to an Array
tempArr.forEach(changeLetter);/*Not many use this but this is the referred way of using loops in javascript*/
str = tempArr.join("");
// code goes here
return str;
}
function changeLetter(ele,index,arr) {
var lowerLetters ="abcdefghijklmnopqrstuvwxyza";
var upperLetters ="ABCDEFGHIJKLMNOPQRSTUVWXYZA";
var lowLetterArr = lowerLetters.split("");
var upLetterArr = upperLetters.split("");
var i =0;
for(i;i<lowLetterArr.length;i++){
if(arr[index] === lowLetterArr[i]){
arr[index] = lowLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
if(arr[index] === upLetterArr[i]){
arr[index] = upLetterArr[i+1];
arr[index]=arr[index].replace(/[aeiou]/g,arr[index].toUpperCase());
return false;
}
}
}
// keep this function call here
// to see how to enter arguments in JavaScript scroll down
LetterChanges(readline());
I have string
var string = .row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4 .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv
and i need to remove all plus sign leaving the plus sign inside the brackets from the string using javascript
I'd go with something along those lines:
var i, splits, string = ".row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4 .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv";
splits = string.split(/(\([^)]+\))/);
for (i = 0; i< splits.length; i++) {
if (splits[i].charAt(0) !== "(") {
splits[i] = splits[i].replace("+"," ");
}
}
string = splits.join();
Another way around (dunno if it's better performance wise) would be to use the following:
var string = ".row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4 .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv";
function replacer (match, offset, string) {
var posOpen = string.indexOf("(",offset);
var posClose = string.indexOf(")",offset);
// we replace it if there are no more closing parenthesis or if there is one that is located after an opening one.
if (posClose === -1 || (posClose > posOpen && posOpen !== -1)) {
return " ";
} else {
return "+";
}
};
string.replace(/\+/g, replacer);
EDIT: added bergi suggestion for a quicker check inside the loop.
EDIT2: Second solution
Use the following code, and let me know if it works :)
var myString = ".row-4 .col-2.grid-unit+.grid-unit+.grid-unit,.row-4:nth-of-type(2n+3) .col-3 .grid-unit .row-4 .grid-unit:nth-of-type(2n+3) .show-grid+.show-grid-reportdiv";
var myArray = myString.split(/\(.[\(\)A-Za-z0-9-.+]*\)/);
for(var i = 0; i < myArray.length; i++) {
myString = myString.replace(myArray[i], myArray[i].replace(/[+]/g,' '));
}
I have a string. It's just like;
var str = "This is an example sentence, thanks.";
I want to change every fifth element of this string.
for(var i=5; i<=str.length; i=i+5)
{
str[i]='X'; // it doesn't work, I need something like that
}
So I want str to be "ThisXis aX exaXple XenteXce, XhankX."
Is there any way to do that?
Use RegEx
str = str.replace(/(....)./g, "$1X")
jsfiddle
var str = "This is an example sentence, thanks.";
var newString = "";
for(var i=0; i<str.length; i++)
{
if ((i % 5) == 4) {
newString += "X";
} else {
newString += str.charAt(i);
}
}
Here is a running example. http://jsfiddle.net/WufuK/1
You could use a map, although the regex solution looks better.
str = str.split('').map(function(chr, index){
return (index % 5 === 4)? 'X' : chr;
}).join('');
You can use string.substring()
var a = "This is an example sentence, thanks.";
var result ="";
for(var i=0;i <a.length-1; i+=5){
result +=a.substr(i, 4)+'X';
}
alert(result)
jsFiddle: http://jsfiddle.net/mVb4u/5
This approach uses Array.reduce, which is native to JavaScript 1.8, but can be backported.
Array.prototype.reduce.call("This is an example sentence, thanks.", function(p,c,i,a) { return p + ( i % 5 == 4 ? "X" : c); });
Update: Updated to reflect am not i am's comments below.
Using JavaScript, I need to check if a given string contains a sequence of repeated letters, like this:
"aaaaa"
How can I do that?
You can use this function:
function hasRepeatedLetters(str) {
var patt = /^([a-z])\1+$/;
var result = patt.test(str);
return result;
}
Use regular expressions:
var hasDuplicates = (/([a-z])\1/i).test(str)
Or if you don't want to catch aA and the likes
var hasDuplicates = (/([a-zA-Z])\1/).test(str)
Or, if you've decided you want to clarify your question:
var hasDuplicates = (/^([a-zA-Z])\1+$/).test(str)
This will check if the string has repeats more than twice:
function checkStr(str) {
str = str.replace(/\s+/g,"_");
return /(\S)(\1{2,})/g.test(str);
}
Try using this
checkRepeat = function (str) {
var repeats = /(.)\1/;
return repeats.test(str)
}
Sample usage
if(checkRepeat ("aaaaaaaa"))
alert('Has Repeat!')
function check(str) {
var tmp = {};
for(var i = str.length-1; i >= 0; i--) {
var c = str.charAt(i);
if(c in tmp) {
tmp[c] += 1;
}
else {
tmp[c] = 1;
}
}
var result = {};
for(c in tmp) {
if(tmp.hasOwnProperty(c)) {
if(tmp[c] > 1){
result[c] = tmp[c];
}
}
}
return result;
}
then you can check the result to get the repeated chars and their frequency. if result is empty, there is no repeating there.
I solved that using a for loop, not with regex
//This check if a string has 3 repeated letters, if yes return true, instead return false
//If you want more than 3 to check just add another validation in the if check
function stringCheck (string) {
for (var i = 0; i < string.length; i++)
if (string[i]===string[i+1] && string[i+1]===string[i+2])
return true
return false
}
var str1 = "hello word" //expected false
var str2 = "helllo word" //expredted true
var str3 = "123 blAAbA" //exprected false
var str4 = "hahaha haaa" //exprected true
console.log(str1, "<==", stringCheck(str1))
console.log(str2, "<==", stringCheck(str2))
console.log(str3, "<==", stringCheck(str3))
console.log(str4, "<==", stringCheck(str4))
var char = "abcbdf..,,ddd,,,d,,,";
var tempArry={};
for (var i=0; i < char.length; i++) {
if (tempArry[char[i]]) {
tempArry[char[i]].push(char[i]);
} else {
tempArry[char[i]] = [];
tempArry[char[i]].push(char[i]);
}
}
console.log(tempArry);
This will even return the number of repeated characters also.