Coderbyte Challenge 4: Letter Changes - Won't Upper Case - javascript

I'm having trouble with Coderbyte's challenge
Using the JavaScript language, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.
Here's my code:
function LetterChanges(str) {
str = str.toLowerCase();
var al = "abcdefghijklmnopqrstuvwxyz";
var vo = "aeiou";
var newStr = "";
for (var i = 0;i < str.length;i++) {
if (al.charAt(al.indexOf(str.charAt(i))) == "z") {
newStr += "A";
}
else if (str.charAt(i) == " "){
newStr += " ";
}
else {
if (al.charAt(al.indexOf(str.charAt(i))+1) == vo.charAt(vo.indexOf(str.charAt(i)))) {
newStr += vo.charAt(vo.indexOf(str.charAt(i))+1).toUpperCase();
}
else {
newStr += al.charAt(al.indexOf(str.charAt(i))+1)
}
}
}
console.log(newStr);
}
LetterChanges("Argument goes here")
This is returning the following into the console:
bshvnfou hpft ifsf
but what I need to be returned is:
bshvnfOU hpft Ifsf
I can't figure out why my .toUpperCase() isn't working. Any help that you can provide is very much appreciated!

Your problem isn't that toUpperCase() isn't working, it's that your code never gets to that point.
Your
if (al.charAt(al.indexOf(str.charAt(i))+1) == vo.charAt(vo.indexOf(str.charAt(i))))
never passes, because of that +1. There's no need for that there, and if you remove it, uppercase vowels will appear. There are other problems with your code beyond that point, but I'll let you solve them as part of the challenge :-)

Wow, it's crazy looking at the code I wrote a year ago! Reviewing this question, here's what I came up with (disclaimer: still getting comfortable with ES6):
function convertText (str) {
const al = 'abcdefghijklmnopqrstuvwxyz';
return str.toLowerCase().split('').map(letter => {
if (letter.match(/\W/)) return letter;
const index = al.indexOf(letter),
newLetter = (al[index + 1] || al[0]);
return newLetter.match(/[aeiou]/) ? newLetter.toUpperCase() : newLetter;
}).join('');
}
And by using character codes:
function letterChanges (str) {
const v = {d: 69, h: 73, n: 79, t: 85, z: 65};
return str.toLowerCase().split('').map(l =>
(l.match(/\W/) ? l : String.fromCharCode(v[l] || l.charCodeAt(0) + 1))
).join('');
}
There're probably better ways, but still a fun question! Thanks again for your help, #MattDiamant

Here's my solution. It does not satisfy the z becomes a requirement but it passes Coderbyte's test as seen in the screenshot below.
function LetterChanges(str) {
return str
.replace(/[a-z]/gi, c => String.fromCharCode(c.charCodeAt(0) + 1))
.replace(/[aeiou]/gi, c => c.toUpperCase());
}
// keep this function call here
LetterChanges(readline());
Letter Changes Javascript Solution

To account for the non-[a-z] characters can toss this in the if statement and it will account for white space and [^a-z]:
if (letter.match(/[^a-z]/)) return letter;

Related

Is There any any javascript (js) function for capitalizing string? [duplicate]

I'm trying to write a function that capitalizes the first letter of every word in a string (converting the string to title case).
For instance, when the input is "I'm a little tea pot", I expect "I'm A Little Tea Pot" to be the output. However, the function returns "i'm a little tea pot".
This is my code:
function titleCase(str) {
var splitStr = str.toLowerCase().split(" ");
for (var i = 0; i < splitStr.length; i++) {
if (splitStr.length[i] < splitStr.length) {
splitStr[i].charAt(0).toUpperCase();
}
str = splitStr.join(" ");
}
return str;
}
console.log(titleCase("I'm a little tea pot"));
You are not assigning your changes to the array again, so all your efforts are in vain. Try this:
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
// You do not need to check if i is larger than splitStr length, as your for does that for you
// Assign it back to the array
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
// Directly return the joined string
return splitStr.join(' ');
}
document.write(titleCase("I'm a little tea pot"));
You are making complex a very easy thing. You can add this in your CSS:
.capitalize {
text-transform: capitalize;
}
In JavaScript, you can add the class to an element
document.getElementById("element").className = "capitalize";
ECMAScript 6 version:
const toTitleCase = (phrase) => {
return phrase
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};
let result = toTitleCase('maRy hAd a lIttLe LaMb');
console.log(result);
Shortest One Liner (also extremely fast):
text.replace(/(^\w|\s\w)/g, m => m.toUpperCase());
Explanation:
^\w : first character of the string
| : or
\s\w : first character after whitespace
(^\w|\s\w) Capture the pattern.
g Flag: Match all occurrences.
If you want to make sure the rest is in lowercase:
text.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
Example usage:
const toTitleCase = str => str.replace(/(^\w|\s\w)(\S*)/g, (_,m1,m2) => m1.toUpperCase()+m2.toLowerCase())
console.log(toTitleCase("heLLo worLd"));
I think this way should be faster; cause it doesn't split string and join it again; just using regex.
var str = text.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
Explanation:
(^\w{1}): match first char of string
|: or
(\s{1}\w{1}): match one char that came after one space
g: match all
match => match.toUpperCase(): replace with can take function, so; replace match with upper case match
If you can use a third-party library then Lodash has a helper function for you.
https://lodash.com/docs/4.17.3#startCase
_.startCase('foo bar');
// => 'Foo Bar'
_.startCase('--foo-bar--');
// => 'Foo Bar'
_.startCase('fooBar');
// => 'Foo Bar'
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>
In ECMAScript 6, a one-line answer using the arrow function:
const captialize = words => words.split(' ').map( w => w.substring(0,1).toUpperCase()+ w.substring(1)).join(' ')
ECMAScript 6 version:
title
.split(/ /g).map(word =>
`${word.substring(0,1).toUpperCase()}${word.substring(1)}`)
.join(" ");
𝗙𝗮𝘀𝘁𝗲𝘀𝘁 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗙𝗼𝗿 𝗟𝗮𝘁𝗶𝗻-𝗜 𝗖𝗵𝗮𝗿𝗮𝗰𝘁𝗲𝗿𝘀
You could simply use a regular expression function to change the capitalization of each letter. With V8 JIST optimizations, this should prove to be the fast and memory efficient.
// Only works on Latin-I strings
'tHe VeRy LOOong StRINg'.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, function(x){return x[0]==="'"||x[0]==="_"?x:String.fromCharCode(x.charCodeAt(0)^32)})
Or, as a function:
// Only works for Latin-I strings
var fromCharCode = String.fromCharCode;
var firstLetterOfWordRegExp = /\b[a-z]|['_][a-z]|\B[A-Z]/g;
function toLatin1UpperCase(x){ // avoid frequent anonymous inline functions
var charCode = x.charCodeAt(0);
return charCode===39 ? x : fromCharCode(charCode^32);
}
function titleCase(string){
return string.replace(firstLetterOfWordRegExp, toLatin1UpperCase);
}
According to this benchmark, the code is over 33% faster than the next best solution in Chrome.
𝗗𝗲𝗺𝗼
<textarea id="input" type="text">I'm a little tea pot</textarea><br /><br />
<textarea id="output" type="text" readonly=""></textarea>
<script>
(function(){
"use strict"
var fromCode = String.fromCharCode;
function upper(x){return x[0]==="'"?x:fromCode(x.charCodeAt(0) ^ 32)}
(input.oninput = function(){
output.value = input.value.replace(/\b[a-z]|['_][a-z]|\B[A-Z]/g, upper);
})();
})();
</script>
text-transform: capitalize;
CSS has got it :)
Also a good option (particularly if you're using freeCodeCamp):
function titleCase(str) {
var wordsArray = str.toLowerCase().split(/\s+/);
var upperCased = wordsArray.map(function(word) {
return word.charAt(0).toUpperCase() + word.substr(1);
});
return upperCased.join(" ");
}
I usually prefer not to use regexp because of readability and also I try to stay away from loops. I think this is kind of readable.
function capitalizeFirstLetter(string) {
return string && string.charAt(0).toUpperCase() + string.substring(1);
};
This routine will handle hyphenated words and words with apostrophe.
function titleCase(txt) {
var firstLtr = 0;
for (var i = 0;i < text.length;i++) {
if (i == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
firstLtr = 2;
if (firstLtr == 0 &&/[a-zA-Z]/.test(text.charAt(i)))
firstLtr = 2;
if (firstLtr == 1 &&/[^a-zA-Z]/.test(text.charAt(i))){
if (text.charAt(i) == "'") {
if (i + 2 == text.length &&/[a-zA-Z]/.test(text.charAt(i + 1)))
firstLtr = 3;
else if (i + 2 < text.length &&/[^a-zA-Z]/.test(text.charAt(i + 2)))
firstLtr = 3;
}
if (firstLtr == 3)
firstLtr = 1;
else
firstLtr = 0;
}
if (firstLtr == 2) {
firstLtr = 1;
text = text.substr(0, i) + text.charAt(i).toUpperCase() + text.substr(i + 1);
}
else {
text = text.substr(0, i) + text.charAt(i).toLowerCase() + text.substr(i + 1);
}
}
}
titleCase("pAt o'Neil's");
// returns "Pat O'Neil's";
You can use modern JS syntax which can make your life much easier. Here is my code snippet for the given problem:
const capitalizeString = string => string.split(' ').map(item => item.replace(item.charAt(0), item.charAt(0).toUpperCase())).join(' ');
capitalizeString('Hi! i am aditya shrivastwa')
function LetterCapitalize(str) {
return str.split(" ").map(item=>item.substring(0,1).toUpperCase()+item.substring(1)).join(" ")
}
let cap = (str) => {
let arr = str.split(' ');
arr.forEach(function(item, index) {
arr[index] = item.replace(item[0], item[0].toUpperCase());
});
return arr.join(' ');
};
console.log(cap("I'm a little tea pot"));
Fast Readable Version see benchmark http://jsben.ch/k3JVz
ES6 syntax
const captilizeAllWords = (sentence) => {
if (typeof sentence !== "string") return sentence;
return sentence.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
captilizeAllWords('Something is going on here')
Or it can be done using replace(), and replace each word's first letter with its "upperCase".
function titleCase(str) {
return str.toLowerCase().split(' ').map(function(word) {
return word.replace(word[0], word[0].toUpperCase());
}).join(' ');
}
titleCase("I'm a little tea pot");
Here a simple one-liner
const ucFirst = t => t.replace(/(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g, c => c.toUpperCase());
Note that it only changes case of first letter of every word, you might want to use it as so:
console.log(ucFirst('foO bAr'));
// FoO BAr
console.log(ucFirst('foO bAr'.toLowerCase()));
// Foo Bar
// works with accents too
console.log(ucFirst('éfoO bAr'));
// ÉfoO BAr
Or based on String.prototype here is one that handles several modes:
String.prototype.ucFirst = function (mode = 'eachWord') {
const modes = {
eachWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/g,
firstWord: /(^|\s)[A-Za-zÀ-ÖØ-öø-ÿ]/,
firstChar: /^[A-Za-zÀ-ÖØ-öø-ÿ]/,
firstLetter: /[A-Za-zÀ-ÖØ-öø-ÿ]/,
};
if (mode in modes) {
return this.replace(modes[mode], c => c.toUpperCase());
} else {
throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: ` + Object.keys(modes).join('|');
}
};
console.log('eachWord', 'foO bAr'.ucFirst());
// FoO BAr
console.log('eachWord', 'foO bAr'.toLowerCase().ucFirst());
// Foo Bar
console.log('firstWord', '1foO bAr'.ucFirst('firstWord'));
// 1foO BAr
console.log('firstChar', '1foO bAr'.ucFirst('firstChar'));
// 1foO bAr
console.log('firstLetter', '1foO bAr'.ucFirst('firstLetter'));
// 1FoO bAr
Edit:
Or based on String.prototype one that handles several modes and an optional second argument to specify word separators (String or RegExp):
String.prototype.ucFirst = function (mode = 'eachWord', wordSeparator = /\s/) {
const letters = /[A-Za-zÀ-ÖØ-öø-ÿ]/;
const ws =
'^|' +
(wordSeparator instanceof RegExp
? '(' + wordSeparator.source + ')'
: // sanitize string for RegExp https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex#comment52837041_6969486
'[' + wordSeparator.replace(/[[{}()*+?^$|\]\.\\]/g, '\\$&') + ']');
const r =
mode === 'firstLetter'
? letters
: mode === 'firstChar'
? new RegExp('^' + letters.source)
: mode === 'firstWord' || mode === 'eachWord'
? new RegExp(
'(' + ws + ')' + letters.source,
mode === 'eachWord' ? 'g' : undefined
)
: undefined;
if (r) {
return this.replace(r, (c) => c.toUpperCase());
} else {
throw `error: ucFirst invalid mode (${mode}). Parameter should be one of: firstLetter|firstChar|firstWord|eachWord`;
}
};
console.log("mike o'hara".ucFirst('eachWord', " \t\r\n\f\v'"));
// Mike O'Hara
console.log("mike o'hara".ucFirst('eachWord', /[\s']/));
// Mike O'Hara
The function below does not change any other part of the string than trying to convert all the first letters of all words (i.e. by the regex definition \w+) to uppercase.
That means it does not necessarily convert words to Titlecase, but does exactly what the title of the question says: "Capitalize First Letter Of Each Word In A String - JavaScript"
Don't split the string
determine each word by the regex \w+ that is equivalent to [A-Za-z0-9_]+
apply function String.prototype.toUpperCase() only to the first character of each word.
function first_char_to_uppercase(argument) {
return argument.replace(/\w+/g, function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
});
}
Examples:
first_char_to_uppercase("I'm a little tea pot");
// "I'M A Little Tea Pot"
// This may look wrong to you, but was the intended result for me
// You may wanna extend the regex to get the result you desire, e.g., /[\w']+/
first_char_to_uppercase("maRy hAd a lIttLe LaMb");
// "MaRy HAd A LIttLe LaMb"
// Again, it does not convert words to Titlecase
first_char_to_uppercase(
"ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples"
);
// "ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples"
first_char_to_uppercase("…n1=orangesFromSPAIN&&n2!='a sub-string inside'");
// "…N1=OrangesFromSPAIN&&N2!='A Sub-String Inside'"
first_char_to_uppercase("snake_case_example_.Train-case-example…");
// "Snake_case_example_.Train-Case-Example…"
// Note that underscore _ is part of the RegEx \w+
first_char_to_uppercase(
"Capitalize First Letter of each word in a String - JavaScript"
);
// "Capitalize First Letter Of Each Word In A String - JavaScript"
Edit 2019-02-07: If you want actual Titlecase (i.e. only the first letter uppercase all others lowercase):
function titlecase_all_words(argument) {
return argument.replace(/\w+/g, function(word) {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
});
}
Examples showing both:
test_phrases = [
"I'm a little tea pot",
"maRy hAd a lIttLe LaMb",
"ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples",
"…n1=orangesFromSPAIN&&n2!='a sub-string inside'",
"snake_case_example_.Train-case-example…",
"Capitalize First Letter of each word in a String - JavaScript"
];
for (el in test_phrases) {
let phrase = test_phrases[el];
console.log(
phrase,
"<- input phrase\n",
first_char_to_uppercase(phrase),
"<- first_char_to_uppercase\n",
titlecase_all_words(phrase),
"<- titlecase_all_words\n "
);
}
// I'm a little tea pot <- input phrase
// I'M A Little Tea Pot <- first_char_to_uppercase
// I'M A Little Tea Pot <- titlecase_all_words
// maRy hAd a lIttLe LaMb <- input phrase
// MaRy HAd A LIttLe LaMb <- first_char_to_uppercase
// Mary Had A Little Lamb <- titlecase_all_words
// ExampleX: CamelCase/UPPERCASE&lowercase,exampleY:N0=apples <- input phrase
// ExampleX: CamelCase/UPPERCASE&Lowercase,ExampleY:N0=Apples <- first_char_to_uppercase
// Examplex: Camelcase/Uppercase&Lowercase,Exampley:N0=Apples <- titlecase_all_words
// …n1=orangesFromSPAIN&&n2!='a sub-string inside' <- input phrase
// …N1=OrangesFromSPAIN&&N2!='A Sub-String Inside' <- first_char_to_uppercase
// …N1=Orangesfromspain&&N2!='A Sub-String Inside' <- titlecase_all_words
// snake_case_example_.Train-case-example… <- input phrase
// Snake_case_example_.Train-Case-Example… <- first_char_to_uppercase
// Snake_case_example_.Train-Case-Example… <- titlecase_all_words
// Capitalize First Letter of each word in a String - JavaScript <- input phrase
// Capitalize First Letter Of Each Word In A String - JavaScript <- first_char_to_uppercase
// Capitalize First Letter Of Each Word In A String - Javascript <- titlecase_all_words
function titleCase(str) {
var myString = str.toLowerCase().split(' ');
for (var i = 0; i < myString.length; i++) {
var subString = myString[i].split('');
for (var j = 0; j < subString.length; j++) {
subString[0] = subString[0].toUpperCase();
}
myString[i] = subString.join('');
}
return myString.join(' ');
}
TypeScript fat arrow FTW
export const formatTitleCase = (string: string) =>
string
.toLowerCase()
.split(" ")
.map((word) => word.charAt(0).toUpperCase() + word.substring(1))
.join(" ");
Here's how you could do it with the map function basically, it does the same as the accepted answer but without the for-loop. Hence, saves you few lines of code.
function titleCase(text) {
if (!text) return text;
if (typeof text !== 'string') throw "invalid argument";
return text.toLowerCase().split(' ').map(value => {
return value.charAt(0).toUpperCase() + value.substring(1);
}).join(' ');
}
console.log(titleCase("I'm A little tea pot"));
A more compact (and modern) rewrite of #somethingthere's proposed solution:
let titleCase = (str => str.toLowerCase().split(' ').map(
c => c.charAt(0).toUpperCase() + c.substring(1)).join(' '));
document.write(titleCase("I'm an even smaller tea pot"));
Below is another way to capitalize the first alphabet of each word in a string.
Create a custom method for a String object by using prototype.
String.prototype.capitalize = function() {
var c = '';
var s = this.split(' ');
for (var i = 0; i < s.length; i++) {
c+= s[i].charAt(0).toUpperCase() + s[i].slice(1) + ' ';
}
return c;
}
var name = "john doe";
document.write(name.capitalize());
This is a perfect example of using modern javascript practices to improve readability. Have not yet seen a reduce version here, but this is what i use. Its both a curried one-liner and very readable
sentence
.trim().toLowerCase()
.split(' ')
.reduce((sentence, word) => `${sentence} ${word[0].toUpperCase()}${word.substring(1)}`, '')
.trim()
With Regex and handling special characters like ñ with multiple spaces in between : /(^.|\s+.)/g
let text = "ñora ñora"
console.log(text.toLowerCase().replace(/(^.|\s+.)/g, m => m.toUpperCase()))
Raw code:
function capi(str) {
var s2 = str.trim().toLowerCase().split(' ');
var s3 = [];
s2.forEach(function(elem, i) {
s3.push(elem.charAt(0).toUpperCase().concat(elem.substring(1)));
});
return s3.join(' ');
}
capi('JavaScript string exasd');
I used replace() with a regular expression:
function titleCase(str) {
var newStr = str.toLowerCase().replace(/./, (x) => x.toUpperCase()).replace(/[^']\b\w/g, (y) => y.toUpperCase());
console.log(newStr);
}
titleCase("I'm a little tea pot")
A complete and simple solution goes here:
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index
+ replacement.length);
}
var str = 'k j g u i l p';
function capitalizeAndRemoveMoreThanOneSpaceInAString() {
for(let i = 0; i < str.length-1; i++) {
if(str[i] === ' ' && str[i+1] !== '')
str = str.replaceAt(i+1, str[i+1].toUpperCase());
}
return str.replaceAt(0, str[0].toUpperCase()).replace(/\s+/g, ' ');
}
console.log(capitalizeAndRemoveMoreThanOneSpaceInAString(str));

How can i print only letters?

I'm trying to do a caesar cipher in javascript, I'm very new at this. I know i have to limit the ascii so that it's only letters. Because like this if we insert the letter "z" and the key "3" it won't give us "c", but something else. I've tried to search but i can't seem to understand how to do that. Thanks in advance for any help.
var letter=readLine("letter?");
var key=parseInt(readLine("key?"));
var result= letter.charCodeAt(0)+key;
print(String.fromCharCode(result));
If I understand correctly, it should work:
for(var i =0; i<letter.length;i++){
print(String.fromCharCode(letter.charCodeAt(i) + key))
}
I know this is an outdated question but since no one has posted the answer:
To shift only letters you can use this:
caesarCipher = (s, k) => {
let string = s;
string = string.replace(/[a-z]/g, str => String.fromCharCode((str.charCodeAt(0) - 97 + k) % 26 + 97));
string = string.replace(/[A-Z]/g, str => String.fromCharCode((str.charCodeAt(0) - 65 + k) % 26 + 65));
return string;
}

Replace all occurences of ('content') from first bracket - ( to VERY last )?

I have a string that may be: Hello (hiii(1998 overhill) hpp) there.
I want to strip to remove the brackets and content from within but keeping the words Hello there.
Below is my code but it removes the first part: (hiii(1998 overhill) leaving hpp) behind.
myString = "Hello (hiii(1998 overhill) hpp) there";
myString = myString.replace(/ \([^)]*\)/g, '');
With that said, i want it to do this for all occurrences which is why i supplied the /g but how do i do it for the last occurrence of (content) hi) also? For future reference.
So if i have "Hello (ddd(dog) kk) and hello (pineapple(g)" is it possible to cut out the last bracket so im left with: Hello (ddd(dog) kk) and hello removing the (pineapple(g)?
Thanks!
I found two ways of possible situations you want.
One of them is the one that I told you in the comment:
var myString = 'Hello (ddd(dog) kk) and hello (pineapple(g)';
console.log(myString.replace(/\(.+\)/g, ''));
This one will remove from the first ( to the last ).
Or removing pairs of brackets contents recursively:
function removeBracketsContents(str) {
while (str.indexOf('(') > -1 & str.indexOf(')') > -1) {
str = str.replace(/\([^\(\)]+\)/g, '');
}
return str;
}
console.log(removeBracketsContents('Hello (hiii(1998 overhill) hpp) there'));
console.log(removeBracketsContents('Hello (ddd(dog) kk) and hello (pineapple(g))'));
Using simple regex may not be suitable to deal with nested structures. Try recursion or regex-recursion instead as shown in the two first answers for this similar question.
Here is a non-regex version of code that will work on all examples given:
var newStr = str.split(' ').map(function(sec) {
if (sec[0] !== '(' && sec[sec.length-1] !== ')' ) {
return sec
}
}).join(' ').replace(/\s\s+/g, ' ')
However, it will not work if there is a word surrounded by white spaces in the original string. That means for the string: Hello (hiii(1998 Teddybear overhill) hpp) there it would return Hello Teddybear there.
Since you did not specify that, the code will take care of all the supplied cases.
Just split the string into an array based on spaces, and add elements at zero position and last position:
myString = myString.split(" ");
var result = myString[0] + " " + myString[myString.length-1];
Not sure if I understood the question correctly but you seem to want to remove everything within the braces also if there is an uneven amount of braces. This is probably an overkill but here is my attempt
JSbin example
myString = "Hello (hiii(1998 overhill) hpp) there";
function noBraces(str){
let arr = str.split('')
openBrace = null,
closeBrace = null;
// find first opening brace
for (let i = 0, l = arr.length; i < l; i++){
if (arr[i] == "(" ) {
openBrace = i;
break
}
}
// find last closing brace
for (let i = 0, l = arr.length - 1; i <= l; l--){
if (arr[l] == ")") {
// we don't need the brace in the result
closeBrace = l + 1;
break
}
}
// check if both braces exist and return result
if (openBrace != null && closeBrace != null){
return str.slice(0,openBrace) + str.slice(closeBrace, str.length);
}
// if only one brace exists then return everything
// on one side of the brace
else if (openBrace != null && closeBrace == null){
return str.slice(0,openBrace);
} else if (openBrace == null && closeBrace != null){
return str.slice(closeBrace,str.length);
} else {
// if no braces found return the string
return str;
}
}
console.log(noBraces(myString));

How to write palindrome in JavaScript

I wonder how to write palindrome in javascript, where I input different words and program shows if word is palindrome or not. For example word noon is palindrome, while bad is not.
Thank you in advance.
function palindrome(str) {
var len = str.length;
var mid = Math.floor(len/2);
for ( var i = 0; i < mid; i++ ) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
palindrome will return if specified word is palindrome, based on boolean value (true/false)
UPDATE:
I opened bounty on this question due to performance and I've done research and here are the results:
If we are dealing with very large amount of data like
var abc = "asdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfdasdhfkahkjdfhkaksjdfhaksdfjhakjddfhkjahksdhfaiuyqewiuryiquweyriyqiuweyriuqiuweryiquweyriuqyweirukajsdhfkahdfjkhakjsdhfkahksdhfakhdjkfqwiueryqiueyriuasdkfjhakjhdfkjashfkajhsdfkjahsdkalsdjflkasjdfljqoiweurasldjflasfd";
for ( var i = 0; i < 10; i++ ) {
abc += abc; // making string even more larger
}
function reverse(s) { // using this method for second half of string to be embedded
return s.split("").reverse().join("");
}
abc += reverse(abc); // adding second half string to make string true palindrome
In this example palindrome is True, just to note
Posted palindrome function gives us time from 180 to 210 Milliseconds (in current example), and the function posted below
with string == string.split('').reverse().join('') method gives us 980 to 1010 Milliseconds.
Machine Details:
System: Ubuntu 13.10
OS Type: 32 Bit
RAM: 2 Gb
CPU: 3.4 Ghz*2
Browser: Firefox 27.0.1
Try this:
var isPalindrome = function (string) {
if (string == string.split('').reverse().join('')) {
alert(string + ' is palindrome.');
}
else {
alert(string + ' is not palindrome.');
}
}
document.getElementById('form_id').onsubmit = function() {
isPalindrome(document.getElementById('your_input').value);
}
So this script alerts the result, is it palindrome or not. You need to change the your_id with your input id and form_id with your form id to get this work.
Demo!
Use something like this
function isPalindrome(s) {
return s === s.split("").reverse().join("") ? true : false;
}
alert(isPalindrome("noon"));
alternatively the above code can be optimized as [updated after rightfold's comment]
function isPalindrome(s) {
return s === s.split("").reverse().join("");
}
alert(isPalindrome("malayalam"));
alert(isPalindrome("english"));
Faster Way:
-Compute half the way in loop.
-Store length of the word in a variable instead of calculating every time.
EDIT:
Store word length/2 in a temporary variable as not to calculate every time in the loop as pointed out by (mvw) .
function isPalindrome(word){
var i,wLength = word.length-1,wLengthToCompare = wLength/2;
for (i = 0; i <= wLengthToCompare ; i++) {
if (word.charAt(i) != word.charAt(wLength-i)) {
return false;
}
}
return true;
}
Let us start from the recursive definition of a palindrome:
The empty string '' is a palindrome
The string consisting of the character c, thus 'c', is a palindrome
If the string s is a palindrome, then the string 'c' + s + 'c' for some character c is a palindrome
This definition can be coded straight into JavaScript:
function isPalindrome(s) {
var len = s.length;
// definition clauses 1. and 2.
if (len < 2) {
return true;
}
// note: len >= 2
// definition clause 3.
if (s[0] != s[len - 1]) {
return false;
}
// note: string is of form s = 'a' + t + 'a'
// note: s.length >= 2 implies t.length >= 0
var t = s.substr(1, len - 2);
return isPalindrome(t);
}
Here is some additional test code for MongoDB's mongo JavaScript shell, in a web browser with debugger replace print() with console.log()
function test(s) {
print('isPalindrome(' + s + '): ' + isPalindrome(s));
}
test('');
test('a');
test('ab');
test('aa');
test('aab');
test('aba');
test('aaa');
test('abaa');
test('neilarmstronggnortsmralien');
test('neilarmstrongxgnortsmralien');
test('neilarmstrongxsortsmralien');
I got this output:
$ mongo palindrome.js
MongoDB shell version: 2.4.8
connecting to: test
isPalindrome(): true
isPalindrome(a): true
isPalindrome(ab): false
isPalindrome(aa): true
isPalindrome(aab): false
isPalindrome(aba): true
isPalindrome(aaa): true
isPalindrome(abaa): false
isPalindrome(neilarmstronggnortsmralien): true
isPalindrome(neilarmstrongxgnortsmralien): true
isPalindrome(neilarmstrongxsortsmralien): false
An iterative solution is:
function isPalindrome(s) {
var len = s.length;
if (len < 2) {
return true;
}
var i = 0;
var j = len - 1;
while (i < j) {
if (s[i] != s[j]) {
return false;
}
i += 1;
j -= 1;
}
return true;
}
Look at this:
function isPalindrome(word){
if(word==null || word.length==0){
// up to you if you want true or false here, don't comment saying you
// would put true, I put this check here because of
// the following i < Math.ceil(word.length/2) && i< word.length
return false;
}
var lastIndex=Math.ceil(word.length/2);
for (var i = 0; i < lastIndex && i< word.length; i++) {
if (word[i] != word[word.length-1-i]) {
return false;
}
}
return true;
}
Edit: now half operation of comparison are performed since I iterate only up to half word to compare it with the last part of the word. Faster for large data!!!
Since the string is an array of char no need to use charAt functions!!!
Reference: http://wiki.answers.com/Q/Javascript_code_for_palindrome
Taking a stab at this. Kind of hard to measure performance, though.
function palin(word) {
var i = 0,
len = word.length - 1,
max = word.length / 2 | 0;
while (i < max) {
if (word.charCodeAt(i) !== word.charCodeAt(len - i)) {
return false;
}
i += 1;
}
return true;
}
My thinking is to use charCodeAt() instead charAt() with the hope that allocating a Number instead of a String will have better perf because Strings are variable length and might be more complex to allocate. Also, only iterating halfway through (as noted by sai) because that's all that's required. Also, if the length is odd (ex: 'aba'), the middle character is always ok.
Best Way to check string is palindrome with more criteria like case and special characters...
function checkPalindrom(str) {
var str = str.replace(/[^a-zA-Z0-9]+/gi, '').toLowerCase();
return str == str.split('').reverse().join('');
}
You can test it with following words and strings and gives you more specific result.
1. bob
2. Doc, note, I dissent. A fast never prevents a fatness. I diet on cod
For strings it ignores special characters and convert string to lower case.
String.prototype.isPalindrome = function isPalindrome() {
const cleanString = this.toLowerCase().replace(/\s+/g, '');
const cleanStringRevers = cleanString.split("").reverse().join("");
return cleanString === cleanStringRevers;
}
let nonPalindrome = 'not a palindrome';
let palindrome = 'sugus';
console.log(nonPalindrome.isPalindrome())
console.log(palindrome.isPalindrome())
The most important thing to do when solving a Technical Test is Don't use shortcut methods -- they want to see how you think algorithmically! Not your use of methods.
Here is one that I came up with (45 minutes after I blew the test). There are a couple optimizations to make though. When writing any algorithm, its best to assume false and alter the logic if its looking to be true.
isPalindrome():
Basically, to make this run in O(N) (linear) complexity you want to have 2 iterators whose vectors point towards each other. Meaning, one iterator that starts at the beginning and one that starts at the end, each traveling inward. You could have the iterators traverse the whole array and use a condition to break/return once they meet in the middle, but it may save some work to only give each iterator a half-length by default.
for loops seem to force the use of more checks, so I used while loops - which I'm less comfortable with.
Here's the code:
/**
* TODO: If func counts out, let it return 0
* * Assume !isPalindrome (invert logic)
*/
function isPalindrome(S){
var s = S
, len = s.length
, mid = len/2;
, i = 0, j = len-1;
while(i<mid){
var l = s.charAt(i);
while(j>=mid){
var r = s.charAt(j);
if(l === r){
console.log('#while *', i, l, '...', j, r);
--j;
break;
}
console.log('#while !', i, l, '...', j, r);
return 0;
}
++i;
}
return 1;
}
var nooe = solution('neveroddoreven'); // even char length
var kayak = solution('kayak'); // odd char length
var kayaks = solution('kayaks');
console.log('#isPalindrome', nooe, kayak, kayaks);
Notice that if the loops count out, it returns true. All the logic should be inverted so that it by default returns false. I also used one short cut method String.prototype.charAt(n), but I felt OK with this as every language natively supports this method.
This function will remove all non-alphanumeric characters (punctuation, spaces, and symbols) and turn everything lower case in order to check for palindromes.
function palindrome(str){
var re = /[^A-Za-z0-9]/g;
str = str.toLowerCase().replace(re, '');
return str == str.split('').reverse().join('') ? true : false;
}
Here is an optimal and robust solution for checking string palindrome using ES6 features.
const str="madam"
var result=[...str].reduceRight((c,v)=>((c+v)))==str?"Palindrome":"Not Palindrome";
console.log(result);
Try this
isPalindrome = (string) => {
if (string === string.split('').reverse().join('')) {
console.log('is palindrome');
}
else {
console.log('is not palindrome');
}
}
isPalindrome(string)
Here's a one-liner without using String.reverse,
const isPal = str => [...new Array(strLen = str.length)]
.reduce((acc, s, i) => acc + str[strLen - (i + 1)], '') === str;
function palindrome(str) {
var lenMinusOne = str.length - 1;
var halfLen = Math.floor(str.length / 2);
for (var i = 0; i < halfLen; ++i) {
if (str[i] != str[lenMinusOne - i]) {
return false;
}
}
return true;
}
Optimized for half string parsing and for constant value variables.
I think following function with time complexity of o(log n) will be better.
function palindrom(s){
s = s.toString();
var f = true; l = s.length/2, len = s.length -1;
for(var i=0; i < l; i++){
if(s[i] != s[len - i]){
f = false;
break;
}
}
return f;
}
console.log(palindrom(12321));
Here's another way of doing it:
function isPalin(str) {
str = str.replace(/\W/g,'').toLowerCase();
return(str==str.split('').reverse().join(''));
}
Below code tells how to get a string from textBox and tell you whether it is a palindrome are not & displays your answer in another textbox
<html>
<head>
<meta charset="UTF-8"/>
<link rel="stylesheet" href=""/>
</head>
<body>
<h1>1234</h1>
<div id="demo">Example</div>
<a accessKey="x" href="http://www.google.com" id="com" >GooGle</a>
<h1 id="tar">"This is a Example Text..."</h1>
Number1 : <input type="text" name="txtname" id="numb"/>
Number2 : <input type="text" name="txtname2" id="numb2"/>
Number2 : <input type="text" name="txtname3" id="numb3" />
<button type="submit" id="sum" onclick="myfun()" >count</button>
<button type="button" id="so2" onclick="div()" >counnt</button><br/><br/>
<ol>
<li>water</li>
<li>Mazaa</li>
</ol><br/><br/>
<button onclick="myfun()">TryMe</button>
<script>
function myfun(){
var pass = document.getElementById("numb").value;
var rev = pass.split("").reverse().join("");
var text = document.getElementById("numb3");
text.value = rev;
if(pass === rev){
alert(pass + " is a Palindrome");
}else{
alert(pass + " is Not a Palindrome")
}
}
</script>
</body>
</html>
25x faster + recursive + non-branching + terse
function isPalindrome(s,i) {
return (i=i||0)<0||i>=s.length>>1||s[i]==s[s.length-1-i]&&isPalindrome(s,++i);
}
See my complete explanation here.
The code is concise quick fast and understandable.
TL;DR
Explanation :
Here isPalindrome function accepts a str parameter which is typeof string.
If the length of the str param is less than or equal to one it simply returns "false".
If the above case is false then it moves on to the second if statement and checks that if the character at 0 position of the string is same as character at the last place. It does an inequality test between the both.
str.charAt(0) // gives us the value of character in string at position 0
str.slice(-1) // gives us the value of last character in the string.
If the inequality result is true then it goes ahead and returns false.
If result from the previous statement is false then it recursively calls the isPalindrome(str) function over and over again until the final result.
function isPalindrome(str){
if (str.length <= 1) return true;
if (str.charAt(0) != str.slice(-1)) return false;
return isPalindrome(str.substring(1,str.length-1));
};
document.getElementById('submit').addEventListener('click',function(){
var str = prompt('whats the string?');
alert(isPalindrome(str))
});
document.getElementById('ispdrm').onsubmit = function(){alert(isPalindrome(document.getElementById('inputTxt').value));
}
<!DOCTYPE html>
<html>
<body>
<form id='ispdrm'><input type="text" id="inputTxt"></form>
<button id="submit">Click me</button>
</body>
</html>
function palindrome(str) {
var re = /[^A-Za-z0-9]/g;
str = str.toLowerCase().replace(re, '');
var len = str.length;
for (var i = 0; i < len/2; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
Or you could do it like this.
var palindrome = word => word == word.split('').reverse().join('')
How about this one?
function pall (word) {
var lowerCWord = word.toLowerCase();
var rev = lowerCWord.split('').reverse().join('');
return rev.startsWith(lowerCWord);
}
pall('Madam');
str1 is the original string with deleted non-alphanumeric characters and spaces and str2 is the original string reversed.
function palindrome(str) {
var str1 = str.toLowerCase().replace(/\s/g, '').replace(
/[^a-zA-Z 0-9]/gi, "");
var str2 = str.toLowerCase().replace(/\s/g, '').replace(
/[^a-zA-Z 0-9]/gi, "").split("").reverse().join("");
if (str1 === str2) {
return true;
}
return false;
}
palindrome("almostomla");
function isPalindrome(s) {
return s == reverseString(s);
}
console.log((isPalindrome("abcba")));
function reverseString(str){
let finalStr=""
for(let i=str.length-1;i>=0;i--){
finalStr += str[i]
}
return finalStr
}
Frist I valid this word with converting lowercase and removing whitespace and then compare with reverse word within parameter word.
function isPalindrome(input) {
const toValid = input.trim("").toLowerCase();
const reverseWord = toValid.split("").reverse().join("");
return reverseWord == input.toLowerCase().trim() ? true : false;
}
isPalindrome(" madam ");
//true
This answer is easy to read and I tried to explain by using comment. Check the code below for How to write Palindrome in JavaScript.
Step 1: Remove all non-alphanumeric characters (punctuation, spaces and symbols) from Argument string 'str' using replace() and then convert in to lowercase using toLowerCase().
Step 2: Now make string reverse. first split the string into the array using split() then reverse the array using reverse() then make the string by joining array elements using join() .
Step 3: Find the first character of nonAlphaNumeric string using charAt(0).
Step 4: Find the Last character of nonAlphaNumeric string using charAt(length of nonAlphaNumeric string - 1).
Step 5: Use If condition to chack nonAlphaNumeric string and reverse string is same or not.
Step 6: Use another If condition to chack first character of nonAlphaNumeric string is same to Last character of nonAlphaNumeric string.
function palindrome(str) {
var nonAlphaNumericStr = str.replace(/[^0-9A-Za-z]/g, "").toLowerCase(); // output - e1y1e
var reverseStr = nonAlphaNumericStr.split("").reverse().join(""); // output - e1y1e
var firstChar = nonAlphaNumericStr.charAt(0); // output - e
var lastChar = nonAlphaNumericStr.charAt(nonAlphaNumericStr.length - 1); // output - e
if(nonAlphaNumericStr === reverseStr) {
if(firstChar === lastChar) {
return `String is Palindrome`;
}
}
return `String is not Palindrome`;
}
console.log(palindrome("_eye"));
function check(txt)
{
for (var i = txt.length; i >= 0; i--)
if (txt[i] !== txt[txt.length - 1 - i])
return console.log('not palidrome');
return console.log(' palidrome');
}
check('madam');
Note: This is case sensitive
function palindrome(word)
{
for(var i=0;i<word.length/2;i++)
if(word.charAt(i)!=word.charAt(word.length-(i+1)))
return word+" is Not a Palindrome";
return word+" is Palindrome";
}
Here is the fiddle: http://jsfiddle.net/eJx4v/
I am not sure how this JSPerf check the code performance. I just tried to reverse the string & check the values. Please comment about the Pros & Cons of this method.
function palindrome(str) {
var re = str.split(''),
reArr = re.slice(0).reverse();
for (a = 0; a < re.length; a++) {
if (re[a] == reArr[a]) {
return false;
} else {
return true;
}
}
}
JS Perf test

How to convert "camelCase" to "Camel Case"?

I’ve been trying to get a JavaScript regex command to turn something like "thisString" into "This String" but the closest I’ve gotten is replacing a letter, resulting in something like "Thi String" or "This tring". Any ideas?
To clarify I can handle the simplicity of capitalizing a letter, I’m just not as strong with RegEx, and splitting "somethingLikeThis" into "something Like This" is where I’m having trouble.
"thisStringIsGood"
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
displays
This String Is Good
(function() {
const textbox = document.querySelector('#textbox')
const result = document.querySelector('#result')
function split() {
result.innerText = textbox.value
// insert a space before all caps
.replace(/([A-Z])/g, ' $1')
// uppercase the first character
.replace(/^./, (str) => str.toUpperCase())
};
textbox.addEventListener('input', split);
split();
}());
#result {
margin-top: 1em;
padding: .5em;
background: #eee;
white-space: pre;
}
<div>
Text to split
<input id="textbox" value="thisStringIsGood" />
</div>
<div id="result"></div>
I had an idle interest in this, particularly in handling sequences of capitals, such as in xmlHTTPRequest. The listed functions would produce "Xml H T T P Request" or "Xml HTTPRequest", mine produces "Xml HTTP Request".
function unCamelCase (str){
return str
// insert a space between lower & upper
.replace(/([a-z])([A-Z])/g, '$1 $2')
// space before last upper in a sequence followed by lower
.replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
// uppercase the first character
.replace(/^./, function(str){ return str.toUpperCase(); })
}
There's also a String.prototype version in a gist.
This can be concisely done with regex lookahead (live demo):
function splitCamelCaseToString(s) {
return s.split(/(?=[A-Z])/).join(' ');
}
(I thought that the g (global) flag was necessary, but oddly enough, it isn't in this particular case.)
Using lookahead with split ensures that the matched capital letter is not consumed and avoids dealing with a leading space if UpperCamelCase is something you need to deal with. To capitalize the first letter of each, you can use:
function splitCamelCaseToString(s) {
return s.split(/(?=[A-Z])/).map(function(p) {
return p.charAt(0).toUpperCase() + p.slice(1);
}).join(' ');
}
The map array method is an ES5 feature, but you can still use it in older browsers with some code from MDC. Alternatively, you can iterate over the array elements using a for loop.
I think this should be able to handle consecutive uppercase characters as well as simple camelCase.
For example: someVariable => someVariable, but ABCCode != A B C Code.
The below regex works on your example but also the common example of representing abbreviations in camcelCase.
"somethingLikeThis"
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/([A-Z])([a-z])/g, ' $1$2')
.replace(/\ +/g, ' ') => "something Like This"
"someVariableWithABCCode"
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/([A-Z])([a-z])/g, ' $1$2')
.replace(/\ +/g, ' ') => "some Variable With ABC Code"
You could also adjust as above to capitalize the first character.
Lodash handles this nicely with _.startCase()
function spacecamel(s){
return s.replace(/([a-z])([A-Z])/g, '$1 $2');
}
spacecamel('somethingLikeThis')
// returned value: something Like This
A solution that handles numbers as well:
function capSplit(str){
return str.replace(
/(^[a-z]+)|[0-9]+|[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z]|[0-9])/g,
function(match, first){
if (first) match = match[0].toUpperCase() + match.substr(1);
return match + ' ';
}
)
}
Tested here [JSFiddle, no library. Not tried IE]; should be pretty stable.
Try this solution here -
var value = "myCamelCaseText";
var newStr = '';
for (var i = 0; i < value.length; i++) {
if (value.charAt(i) === value.charAt(i).toUpperCase()) {
newStr = newStr + ' ' + value.charAt(i)
} else {
(i == 0) ? (newStr += value.charAt(i).toUpperCase()) : (newStr += value.charAt(i));
}
}
return newStr;
If you don't care about older browsers (or don't mind using a fallback reduce function for them), this can split even strings like 'xmlHTTPRequest' (but certainly the likes of 'XMLHTTPRequest' cannot).
function splitCamelCase(str) {
return str.split(/(?=[A-Z])/)
.reduce(function(p, c, i) {
if (c.length === 1) {
if (i === 0) {
p.push(c);
} else {
var last = p.pop(), ending = last.slice(-1);
if (ending === ending.toLowerCase()) {
p.push(last);
p.push(c);
} else {
p.push(last + c);
}
}
} else {
p.push(c.charAt(0).toUpperCase() + c.slice(1));
}
return p;
}, [])
.join(' ');
}
My version
function camelToSpace (txt) {
return txt
.replace(/([^A-Z]*)([A-Z]*)([A-Z])([^A-Z]*)/g, '$1 $2 $3$4')
.replace(/ +/g, ' ')
}
camelToSpace("camelToSpaceWithTLAStuff") //=> "camel To Space With TLA Stuff"
const value = 'camelCase';
const map = {};
let index = 0;
map[index] = [];
for (let i = 0; i < value.length; i++) {
if (i !== 0 && value[i] === value[i].toUpperCase()) {
index = i;
map[index] = [];
}
if (i === 0) {
map[index].push(value[i].toUpperCase());
} else {
map[index].push(value[i]);
}
}
let resultArray = [];
Object.keys(map).map(function (key, index) {
resultArray = [...resultArray, ' ', ...map[key]];
return resultArray;
});
console.log(resultArray.join(''));
Not regex, but useful to know plain and old techniques like this:
var origString = "thisString";
var newString = origString.charAt(0).toUpperCase() + origString.substring(1);

Categories