Removing all space from an array javascript - javascript

I have an array that I need to remove spaces from, for example it returns like
[book, row boat,rain coat]
However, I would like to remove all the white spaces.
All the guides I saw online said to use .replace, but it seems like that only works for strings. Here is my code so far.
function trimArray(wordlist)
{
for(var i=0;i<wordlist.length;i++)
{
wordlist[i] = wordlist.replace(/\s+/, "");
}
}
I have also tired replace(/\s/g, '');
Any help is greatly appreciated!

First and foremost you need to enclose the words in your array quotes, which will make them into strings. Otherwise in your loop you'll get the error that they're undefined variables. Alternatively this could be achieved in a more terse manner using map() as seen below:
const arr = ['book', 'row boat', 'rain coat'].map(str => str.replace(/\s/g, ''));
console.log(arr);

This will remove all of the spaces, even those within the text:
const result = [' book',' row boat ','rain coat '].map(str => str.replace(/\s/g, ''));
console.log(result);
and this will only remove preceding and trailing spaces:
const result = [' book',' row boat ','rain coat '].map(str => str.trim());
console.log(result);

Related

How do I replace the last letter of a string element in an array with replace()

I've just started coding..I'm a super beginner and have no idea about regex yet so for now I'd rather not use it. This is an exercise I'm trying to solve. The problem is that when a word contains matching characters, the first character gets the lower case, but what I actually want is the last character of the word to become small.
I don't really require a solution for the problem. Instead I'd rather have some insight on what I'm doing wrong and maybe direct me to the right path :)
function alienLanguage(str) {
let bigWords = str.toUpperCase().split(" ");
let lastLetterSmall = [];
bigWords.forEach(words => {
lastLetterSmall
.push(words
.replace(words
.charAt(words.length -1), words.charAt(words.length -1).toLowerCase()));
});
console.log(lastLetterSmall.join(' '));
}
alienLanguage("My name is John");
alienLanguage("this is an example");
alienLanguage("Hello World");
alienLanguage("HELLO WORLD");
Since you only really want to work with indicies of the string - you don't need to replace anything dynamically other than the last index - replace won't work well, since if you pass it a string, it will only replace the first matching letter. For example:
'foo'.replace('o', 'x')
results in 'fxo', because the first o (and only the first o) gets replaced.
For your code, instead of replace, just concatenate the two parts of the string together: the part from index 0 to next-to-last index, and the character at the last index with toLowerCase() called on it:
function alienLanguage(str) {
const result = str
.toUpperCase()
.split(" ")
.map(line => line.slice(0, line.length - 1) + line[line.length - 1].toLowerCase())
.join(' ');
console.log(result);
}
alienLanguage("My name is John");
alienLanguage("this is an example");
alienLanguage("Hello World");
alienLanguage("HELLO WORLD");

How can I cut the word after certain symbols?

I have such a structure "\"item:Test:3:Facebook\"" and I need somehow fetch the word Facebook.
The words can be dynamic. So I need to get word which is after third : and before \
I tried var arr = str.split(":").map(item => item.trim()) but it doesn't do what I need. How can I cut a word that will be after third : ?
A litte extra code to remove the last " aswell.
var str = "\":Test:3:Facebook\"";
var arr = str.split(":").map(item => item.trim());
var thirdItem = arr[3].replace(/[^a-zA-Z]/g, "");
console.log(thirdItem);
If the amount of colons (:) doesn't vary you can simply use an index on the resulting array like this:
var foo = str.split(":")[3];
The word after the 3rd : will be the fourth word returned, so it will be at index 3 in the array returned by split() (arrays being zero-indexed, of course). You might also want to get rid of the trailing quote mark.
Demo:
str = "\"item:Test:3:Facebook\"";
var word = str.split(":")[3].replace("\"", "");
console.log(word);
This should do the trick, plus remove all symbols
var foo = str.split(":")[3].replace(/[^a-zA-Z ]/g, "")

Javascript: split a string according to two criteria?

I am trying to count the number of sentences in a paragraph. In the paragraph, all sentences end with either ''.'' or ''!''.
My idea is to first split the paragraph into strings whenever there's a ''.'' or ''!'' and then count the number of splitted strings.
I have tried
.split('.' || '!')
but that does not work. It only splits strings whenever there is a ''.''
May I know how to deal with this?
Just use a Regexp, it's pretty simple ;)
const example = 'Hello! You should probably use a regexp. Nice isn\'t it?';
console.log(example.split(/[.!]/));
You will need to use a regex for this.
The following should work:
.split(/\.|!/)
You can use regex /\.|!/ in split() as str.split(/\.|!/) :
var str = 'some.string';
console.log(str.split(/\.|!/));
str = 'some.string!name';
console.log(str.split(/\.|!/));
const sampleString = 'I am handsome. Are you sure?! Just kidding. Thank you.';
const result = sampleString.split(/\.|!/)
console.log(result);
// to remove elements that has no value you can do
const noEmptyElements = result.filter(str => str);
console.log(noEmptyElements);
Try below code it will give you an exact count of sentences in the paragraph.
function count(string,char) {
var re = new RegExp(char,"gi");
return string.match(re).length;
}
function myFunction() {
var str = 'but that! does! not work. It only splits strings whenever there is a. ';
console.log(count(str,'[.?!]'));
}

Write a function that counts the number of individual words in a given string argument

I have this problem im trying to solve but i'm having a hard time getting the output I want. This is what I have.
var stringLength = [];
function wordCount(text) {
stringLength.push(text.split(' ').join(' , '))
console.log(stringLength.length)
}
wordCount('All work and no play makes Jack a dull boy');
This should return '10'. Can anyone let me know where I am going wrong?
You're splitting it up, but then you're joining them all back together....so text.split(' ') forms an array on individual words, but then the .join(' , ') joins all the words together into a single string (separated by commas)
It should just be:
function wordCount(text) {
return text.split(' ').length
}
You just need to split on the spaces (' '), that will return an array of words that you can get the length property from:
function wordCount(text) {
return text.split(' ').length;
}
var count = wordCount('All work and no play makes Jack a dull boy'); //10
console.log(count);

reverse string greater than certain length

I am working on a problem where I need to be able to reverse a sentence but only words that are greater than 4 can be reversed. the rest of the words must be the same as they are. I have tried to check to see if length is greater than 4 but that does not return the result I am looking for. All I need is to reverse any words that are greater than 4 in the sentence. Any help is greatly appreciated.
Edit: Here is the simple of what I know how to do. It reverses all of the sentence. I am sure that there needs to be some way to break apart each word and determine the length of the word and then bring the sentence back together, but I don't know how that would be done.
var sentence = "This could be the answer I need";
if (sentence.length > 4) {
console.log( sentence.split('').reverse().join(''));
}
Thank you
In Short:
var s = 'This is a short sentence'
, e = s.split(' ').map(function(v){ return v.length>4?v.split('').reverse().join(''):v; }).join(' ');
console.log(e); // 'This is a trohs ecnetnes'
Explained:
var s = 'This is a short sentence' // set test sentence
, e = s.split(' ') // 'This is a short sentence' ==> ['This','is','a','short','sentence']
.map(function(v,i,a){ // REPLACE the value of the current index in the array (run for each element in the array)
return v.length > 4 // IF the length of the a 'word' in the array is greater than 4
? v.split('') // THEN return: 'word' ==> ['w','o','r','d']
.reverse() // ['w','o','r','d'] ==> ['d','r','o','w']
.join('') // ['d','r','o','w'] ==> 'drow'
: v; // OR return: the original 'word'
}).join(' '); // ['This','is','a','trohs','ecnetnes'] ==> 'This is a trohs ecnetnes'
console.log(e); // 'This is a trohs ecnetnes'
You've not shown us your source code, so its hard to know how far you got. Not wanting to just give you the code, therefore removing the opportunity to learn how to put it together, I suggest that you look into the following things:
The String split() method, which could be used to split your sentence into individual words in an array
Look into how to iterate over an array of your string words in a for-loop, looking for those that are greater than 4 characters long.
Understand how to reverse a string in situ - see this answer. Only apply this to the strings that are over the right size. Make sure you replace your original strings with the reversed ones in the arry.
Then understand how the Array join() method works.
I'm sorry if I've been over-simplistic in my descriptions - but it is hard to understand from your question how much you need this spelled out. Hope this is helpful.
The simplest approach is to do the following:
Split the string on the space. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
The use the forEach function to loop through each element, reversing if the length is > 4 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
Then finish with join to put all the elements of the array into a string (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)
// For word length greater than equal to 5
function reverseString(s){
return s.split(' ').
map( v => {
return v.length > 4 ? v.split('').
reverse().join('') : v;
} ).join(' ');
}
OR
function reverseString(string){
return string.replace(/\w{5,}/g, function(w) { return w.split('').reverse().join('') })
}
Replace with your string word length
Use regex to match words with at least 5 characters, and replace with reversed characters:
var s = "I am working on a problem where I need to be able to reverse a sentence but only words that are greater than 4 can be reversed.";
s2 = s.replace(/\b(\w\w\w\w\w+)\b/g, function(word) {
return word.split("").reverse().join("");
});
console.log(s2);
outputs:
I am gnikrow on a melborp erehw I need to be able to esrever a ecnetnes but only sdrow that are retaerg than 4 can be desrever.
fiddle

Categories