function duplicateEncode(word){
var i;
var j;
for(i = 0; i < word.length; i++) {
for(j = i + 1; j < word.length; j++) {
if (word[i] == word[j]) {
word = word.replace(/word[i]/gi, ')');
}
else word = word.replace(/word[i]/gi, '(');
};
};
return word;
}
I need to get ( if character is not repeated in the word and this ) if it is and this code doesnt work it just gives me the word back that I type in.
You are not using regex properly. Here is one possible solution based off of your original code. As you know, Strings are immutable in Javascript so we need to rebuild the string every time using your approach.
function duplicateEncode(word){
for(i = 0; i < word.length; i++) {
if (word[i] == word[i+1]) {
word = word.substring(0,i) + ')' + word.substring(i+1);
}
else {
word = word.substring(0,i) + '(' + word.substring(i+1);
}
}
return word;
}
To avoid rebuilding the string we can store the characters in an array and then join them at the end for a performance boost for large strings.
function duplicateEncode(word){
const newWordArr = [];
for(i = 0; i < word.length; i++) {
if (word[i] == word[i+1]) {
newWordArr.push(')');
}
else {
newWordArr.push('(');
}
}
return newWordArr.join('');
}
I need string Double each letter in a string
abc -> aabbcc
i try this
var s = "abc";
for(var i = 0; i < s.length ; i++){
console.log(s+s);
}
o/p
> abcabc
> abcabc
> abcabc
but i need
aabbcc
help me
Use String#split , Array#map and Array#join methods.
var s = "abc";
console.log(
// split the string into individual char array
s.split('').map(function(v) {
// iterate and update
return v + v;
// join the updated array
}).join('')
)
UPDATE : You can even use String#replace method for that.
var s = "abc";
console.log(
// replace each charcter with repetition of it
// inside substituting string you can use $& for getting matched char
s.replace(/./g, '$&$&')
)
You need to reference the specific character at the index within the string with s[i] rather than just s itself.
var s = "abc";
var out = "";
for(var i = 0; i < s.length ; i++){
out = out + (s[i] + s[i]);
}
console.log(out);
I have created a function which takes string as an input and iterate the string and returns the final string with each character doubled.
var s = "abcdef";
function makeDoubles(s){
var s1 = "";
for(var i=0; i<s.length; i++){
s1 += s[i]+s[i];
}
return s1;
}
alert(makeDoubles(s));
if you want to make it with a loop, then you have to print s[i]+s[i];
not, s + s.
var s = "abc";
let newS = "";
for (var i = 0; i < s.length; i++) {
newS += s[i] + s[i];
}
console.log(newS);
that works for me, maybe a little bit hardcoded, but I am new too))
good luck
console.log(s+s);, here s holds entire string. You will have to fetch individual character and append it.
var s = "abc";
var r = ""
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
r+= c+c
}
console.log(r)
var doubleStr = function(str) {
str = str.split('');
var i = 0;
while (i < str.length) {
str.splice(i, 0, str[i]);
i += 2;
}
return str.join('');
};
You can simply use one of these two methods:
const doubleChar = (str) => str.split("").map(c => c + c).join("");
OR
function doubleChar(str) {
var word = '';
for (var i = 0; i < str.length; i++){
word = word + str[i] + str[i];
};
return word;
};
function doubleChar(str) {
let sum = [];
for (let i = 0; i < str.length; i++){
let result = (str[i]+str[i]);
sum = sum + result;
}
return sum;
}
console.log (doubleChar ("Hello"));
This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
Closed 7 years ago.
So, I want to convert a string into a Title Case string. I've written this code but I get the same string in lowercase when I run this. Could anyone please point out where I'm wrong with this? Any help is much appreciated.
function capitalize(str) {
return str.toUpperCase();
}
function titleCase(str1) {
str1 = str1.toLowerCase();
var arr = str1.split(' ');
var l = arr.length;
var m;
for (var i = 0; i < l; i++) {
m = arr[i].length;
for (var j = 0; j < m; j++) {
if (j === 0) {
arr[i][0] = capitalize(arr[i][0]);
}
else {
arr[i][j] = arr[i][j];
}
}
}
return arr;
}
titleCase("I'm a little tea potty");
I'm pretty sure you were given advice on exactly this question earlier, but using ES5 methods (you can downgrade it to for loops yourself).
function titleCase(str1) {
return str1.toLowerCase().split(' ').map(function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}).join(' ');
}
document.body.textContent = titleCase("I'm a little tea potty");
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.4.1/es5-shim.min.js"></script>
Now, what's with your code?
function capitalize(str) {
return str.toUpperCase();
}
function titleCase(str1) {
str1 = str1.toLowerCase();
var arr = str1.split(' ');
var l = arr.length;
var m;
for (var i = 0; i < l; i++) {
m = arr[i].length;
for (var j = 0; j < m; j++) {
if (j === 0) {
arr[i][0] = capitalize(arr[i][0]);
} else {
arr[i][j] = arr[i][j];
}
}
}
return arr;
}
document.body.textContent = titleCase("I'm a little tea potty");
Let's look at it bit by bit:
function capitalize(str) {
return str.toUpperCase();
}
Nothing wrong with the above, except that it seems pretty pointless to functionalise.
So, now we have your function, you take an argument (a string) and then you make it all lower cased
function titleCase(str1) {
str1 = str1.toLowerCase();
So here comes your string "I'm a little tea potty" and it becomes "i'm a little tea potty". So far so good. Then you split it at spaces.
var arr = str1.split(' ');
var l = arr.length;
var m;
Along comes your string and becomes var arr = ["i'm","a","little","tea","potty"]; and l becomes 5, the length of this array.
Next you intend to loop through the array arr, that looks fine
for (var i = 0; i < l; i++) {
So for each word (a string) in the array (iteration) you get the length of the string, the first i'm is 3.
m = arr[i].length;
Then you intend to iterate each character in the word, which is fine
for (var j = 0; j < m; j++) {
Then, you are saying if it is the first character of the word then I want a capital letter, otherwise do nothing with it.
if (j === 0) {
arr[i][0] = capitalize(arr[i][0]);
} else {
arr[i][j] = arr[i][j];
}
But here's the problem, you try to write the characters back to the string, which is immutable. No errors are thrown, just nothing changes, it's like the string has a read-only switch, just like on a memory card. So your loops continue on and on, do nothing, until all is done. Then you return the array.
return arr;
And surpirise, it is just the same as when you split the sentence into words. ["i'm","a","little","tea","potty"]
I have changed your code. This will help you ..
function capitalize(str) {
return str.toUpperCase();
}
function titleCase(str1) {
str1 = str1.toLowerCase();
var arr = str1.split(' ');
var l = arr.length;
var m;
for (var i = 0; i < l; i++) {
m = arr[i].length;
arr[i] = capitalize(arr[i][0])+arr[i].substr(1);
}
return arr;
}
titleCase("I'm a little tea potty");
One liner here
function titleCase(str) {
return str.split(' ').map(function(s){
return s.slice(0, 1).toUpperCase() + s.slice(1);
}).join(' ');
}
titleCase("I'm a little tea potty");
My code was work well with string like "The quick brown fox jumped over the lazy dog".
But not work with string like "Google do a barrel roll".
It says problem is "TypeError undefined is not an object(evaluating 'Astr[i].length') ".
function findLongestWord(str) {
var Astr = str.split(" ");
var t = Astr[0].length;
var Al = Astr.length;
var j = 0;
for(var i =1; i < t;i++)
{
if(t < Astr[i].length)
{
t = Astr[i].length;
j = i;
}
}
str = Astr[j];
return str.length;
}
findLongestWord("Google do a barrel roll");
Here is one way of improving your function:
var str = 'Google do a barrel roll';
function findLongestWord(str) {
var Astr = str.split(' ');
if (!Astr.length) {
throw new Error('findLongestWord(): no words in str');
}
var t = Astr[0].length;
var Al = Astr.length;
var j = 0;
for(var i = 0; i < Al; i++)
{
if(t < Astr[i].length)
{
t = Astr[i].length;
j = i;
}
}
str = Astr[j];
return str.length;
}
findLongestWord(str);
//=> 6
You can also do something like this (which is a little easier to understand):
str.split(' ').reduce(function(longest, cur) {
return (cur.length > longest.length) ? cur : longest;
}, '');
//=> Google
you have problem with the variables in your 'for' loop.
As you can see, you split the array and get the length of the first member in the array
So basicly you get the first word length instead of the word count
var Astr = str.split(" ");
var t = Astr[0].length;
Here you can see that you use 't' (the first word length) as your loop bounds.
for(var i =1; i < t;i++)
Keep your code simple & readable this way it will be maintainable.
function findLongestWord(str) {
var words = str.split(" ");
var words_count = words.length;
var longest_word_length = 0;
for(var i = 0; i < words_count; i++){
if(longest_word_length < words[i].length){
longest_word_length = words[i].length;
}
}
return longest_word_length;
}
findLongestWord("Google do a barrel roll");
Note that you always can use short-hand functions for that
function findLongestWord(str) {
return str.split(' ').reduce(function(longest, cur) {
return (cur.length > longest.length) ? cur : longest;
}, '').length;
}
findLongestWord("Google do a barrel roll");
function findLongestWord(str)
{var arr=[];
arr=str.split(' ');
arr=arr.sort(function(a,b)
{
return b.length-a.length; /*sorting the array in decending order of
lengths of each word*/
});
var st=arr[0]; /* obviously the first element of the array will
have longest length.*/
return st.length;
}
findLongestWord("Google do a barrel roll");
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
When I call longestWord("Pride and Prejudice"), it returns 'Pride' and not 'Prejudice' which is the longest word... why? I checked some other similar questions, but the solutions looked a lot like my code.
That's because you're not comparing all the items in the array, you leave out the last one.
for (var i = 0; i < str.length - 1; i++)
should be
for (var i = 0; i < str.length; i++)
or
for (var i = 0; i <= str.length - 1; i++)
One advantage to taking a functional approach to such problems is that you don't even have to keep count
See MDN Array.reduce for more info. (note: reduce needs shim for IE8)
function longer(champ, contender) {
return (contender.length > champ.length) ? contender : champ;
}
function longestWord(str) {
var words = str.split(' ');
return words.reduce(longer);
}
console.log(longestWord("The quick brown fox jumped over the lazy dogs"));
Here this is your solution with a forEach, this will help you avoid the error in the future
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
console.log(longestWord("pride and prejudice"));
Your original problem was just the str.length - 1 should have just been str.length, originally you wouldn't have gotten to the last element of the array
You have a -1 in your condition, it never even scans it:
for (var i = 0; i < str.length - 1; i++) {
Should be:
for (var i = 0; i < str.length; i++) {
Demo: http://jsfiddle.net/LfgFk/
The index is going up to str.length -1:
for (var i = 0; i < str.length - 1; i++) {
So the last word is not processed.
Try with: longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice"). You'll see it works (returns AAAAAAAAAAAAAAAAAAAAAAAAA).
In case you're in doubt, the simplest way to fix it is removing the -1 from the for loop.
for (var i = 0; i < str.length; i++) {
Check a demo with both versions (the problematic and the fixed): link here.
You can simplify your code with a library like Lo-Dash:
function longestWord(string) {
var words = string.split(' ');
return _.max(words, function(word) { return word.length; });
}
ForEach is faster in FF but slower in Chrome,
but for loop with the cached length and function apply/call is quite faster in both FF and chrome.
Hope the below code helps:
function getLongest (arrStr) {
var longest = 0, word;
for(var i=0 , len = arrStr.length ; i < len ; i++){
if(longest < arrStr[i].length) {
longest = arrStr[i].length;
word = arrStr[i];
}
}
return word;
}
function isLongest (str) {
var arrayStr = str.split(' ');
return function(fn) {
return fn.apply(this,[arrayStr]);
}
}
isLongest("hello aaaaaaaaaaaaaaaaaaaaaaaaa bbb")(getLongest); //aaaaaaaaaaaaaaaaaaaaaaaaa
for (var i = 0; i < str.length - 1; i++)
to
for (var i = 0; i <= str.length - 1; i++)
OR
for (var i = 0; i < str.length; i++)
does this solve the problem??
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i <= str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
document.write(longestWord("pride and prejudice"));
I find that the .map method here helps a lot (this is if you want the character count of the word, not the word itself):
function findLongestWord(str) {
var array = str.split(/\s+/);
var wordLength = array.map(function(i) {
return i.length;
});
var largest = Math.max.apply(Math, wordLength);
return largest;
}
I will refer you to this awesome article which defines three ways:
1 - Find the Longest Word With a FOR Loop
function findLongestWord(str) {
var strSplit = str.split(' ');
var longestWord = 0;
for(var i = 0; i < strSplit.length; i++){
if(strSplit[i].length > longestWord){
longestWord = strSplit[i].length;
}
}
return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
2 - Find the Longest Word With the sort() Method
function findLongestWord(str) {
var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
return longestWord[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
3 - Find the Longest Word With the reduce() Method
function findLongestWord(str) {
var longestWord = str.split(' ').reduce(function(longest, currentWord) {
return currentWord.length > longest.length ? currentWord : longest;
}, "");
return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Of course, it returns the length of the biggest word if you want to get the string, just get rid of the length in return part.
function longestWord(sentence){
var arr = sentence.match(/[a-z]+/gi);
arr.sort(function(a, b){
return b.length - a.length;
});
return arr[0];
}
longestWord('hello man##$%');
// ==> output: hello
function LongestWord(sen) {
// code goes here
const wordsArray = sen.split('').map(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c<='9')? c : ' ').join('').split(' ').filter(item => item !== '');
wordsArray.sort((a, b) => a.length < b.length);
return wordsArray[0];
}
Is there a specific reason
for (var i = 0; i < str.length - 1; i++)
isn't
for (var i = 0; i < str.length - 1; i++)
That seems like it could be the cause.
You need to use:
for (var i=0;i<=str.length - 1; i++)
That way it will scan the entire phrase
Thanks everyone, this is the fixed code:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length; i++) {
var checkedLetters = "";
for (var j = 0; j < str[i].length; j++) {
if (/[a-zA-Z]/.test(str[i][j])) {
checkedLetters += str[i][j];
}
if (longest < checkedLetters.length) {
longest = checkedLetters.length;
word = checkedLetters;
}
}
}
return word;
}
This seems to be the easiest way to do this.
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
str.forEach(function(str) {
if (longest < str.length) {
longest = str.length;
word = str;
}
});
return word;
}
I would say using the forEach loop is the most understandable version
function longestWord(sen) {
big_word = ""
words = sen.split(" ")
words.forEach(function(word){
if (word.length > big_word.length){
big_word = word
};
});
return big_word
};
I think this is more easy
function findLongestWord(str) {
var longestStr = 0;
for (var x=0;x<str.split(' ').length;x++){
if (longestStr < str.split(' ')[x].length){
longestStr = str.split(' ')[x].length;
}
}
return longestStr;
}
Here is one other way to solve it.
function findLongestWord(str) {
var result = [];
var one = str.split(" ");
for (var i = 0; i < one.length; i++) {
result[i] = one[i].length;
result.reverse().sort(function(a,b) {
return b-a;
});
}
return result[0];
}
Using the sort() method,this sorts the elements of an array by some ordering criterion and then returns the length of the first element of this array and hence the longest word.
function longest(string){
var longestWord = string.split(' ').sort(function(a,b){
return b.length - a.length;
});
return longestWord[0];
}
TRY THIS
function longest(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i <= str.length - 1; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
Another method is by using sort:
function longestWord(string) {
let longest = 0;
let str = str.split(" ").sort((word1,word2)=>{
});
return str[0].length;
}
longestWord('I love Python ')
Code below will find the largest word and its length from a string.
Code is in plain JavaScript and html.
function findLongestWord() {
var str = document.getElementById('inputText').value;
calculateLength(str);
}
function calculateLength(str) {
var substring = str.split(" ");
var minChar = '';
for (var i = 0; i <= substring.length - 1; i++) {
if (substring[i].length >= minChar.length) {
minChar = substring[i];
}
}
document.getElementById('longChar').innerHTML = 'Longest Word: ' + minChar;
document.getElementById('longCharLength').innerHTML = 'Longest Word length: ' + minChar.length;
}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<input type="text" id="inputText"> <br/>
<button onclick=findLongestWord()>Click to find longest word</button> <br/>
<div id="longChar"></div> <br/>
<div id="longCharLength"></div>
</body>
<script src="longestWord.js"></script>
</html>
function findLongestWord(str) {
let stringArray = str.split(" ");
stringArray.sort(function(a, b){
return a.split('').length < b.split('').length;
})
return stringArray[0];
}
findLongestWord("The quick brown fox jumped over the lazy dog");
function sortNumber(a, b) {
return a - b;
}
function findLongestWordLength(str) {
var split = str.split(" ");
var arr=[];
for(var i=0;i<split.length;i++){
arr.push(split[i].length);
}
arr.sort(sortNumber);
console.log(arr[arr.length-1]);
return(arr[arr.length-1]);
}
findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");
const longestWord = string =>
{
stringArray = string.split(' ').sort(
(a,b) => b.length - a.length)
let longestArray= stringArray.filter( word => word.length === stringArray[0].length )
if(longestArray.length === 1){
console.log(longestArray[0])
}
else
{
console.log(longestArray)
}
}
longestWord("Pride and Prejudice")
// My simple solution.
const findLongestWordLength = str => {
let array = str.split(" ");
let longest = 0;
array.map(e => {
if (e.length > longest) {
longest = e.length;
}
})
return longest;
}
Solutions above are incomplete. What if there r 2 or more words that have same length. here is a better solution:
longest = str => {
let words = str.split(" ");
let size = 0;
let max = [""];
for (let i = 0; i < words.length; i++) {
if (words[i].length > size) {
size = words[i].length;
}
if (max[max.length - 1].length < words[i].length) {
max = [];
max.push(words[i]);
} else {
max = [...max, words[i]];
}
}
return max;
};
For error checking in question, refer this answer
Longest word in String
Using for/forEach loop
function longestWord(str){
const words = str.split(' ');
let longWord = "";
words.forEach((word) => {
if(word.length > longWord.length) { longWord = word }
})
return longWord;
}
Using sort
function longestWord(str) {
return str.split(' ')
.sort((a, b) => b.length - a.length)[0];
}
Using reduce
function longestWord(str){
return str.split(' ')
.reduce((maxWord, curWord) => curWord.length > maxWord.length ? curWord : maxWord );
}
// for loop
function longestWord1(str){
const words = str.split(' ');
let longWord = "";
words.forEach((word) => {
if(word.length > longWord.length) { longWord = word }
})
return longWord;
}
// sort
function longestWord2(str) {
return str.split(' ').sort((a, b) => b.length - a.length)[0];
}
// reduce
function longestWord3(str){
return str.split(' ').reduce((maxWord, curWord) => curWord.length > maxWord.length ? curWord : maxWord );
}
let text;
text = "What if we try a super-long word such as otorhinolaryngology";
console.log(longestWord1(text));//=> "otorhinolaryngology"
text = "";
console.log(longestWord2(text));//=> ""
text = "What "
console.log(longestWord3(text));//=> "What"
text = "What is pen?"
console.log(longestWord1(text));//=> "What"
text = "three four five six twenty one"
console.log(longestWord2(text));//=> "twenty"
text = ("The quick brown fox jumped over the lazy dog")
console.log(longestWord3(text));//=> "jumped"