I have this code:
var name1 = "John James"
var name2 = "Jake Connor Steve"
var name3 = "George"
var name4 = "Michael James Jackson"
What I need to check if each string have more than two words, if the string is bigger than two words then remove the middle words and keep just the first and the last word, so the result would be this:
var name1 = "John James"
var name2 = "Jake Steve"
var name3 = "George"
var name4 = "Michael Jackson"
I don't know how to identify the size of words inside a string, how can I do that ? Any suggestion?
split the string into an array. If the array length is greater than 2 remove the element at the first index with splice. Then return a new joined up string.
function checkRemove(str) {
const arr = str.split(' ');
if (arr.length > 2) arr.splice(1, 1);
return arr.join(' ');
}
console.log(checkRemove('Jake Connor Steve'));
console.log(checkRemove('John James'));
console.log(checkRemove('George'));
console.log(checkRemove('Michael James Jackson'));
const name1 = "John James"
const name2 = "Jake Connor Steve"
const name3 = "George"
const name4 = "Michael James Jackson"
function midRemover(str) {
//First we turn the string into an array by using the .split() so we can find the middle number in the array.
const arr = str.split(" ");
//next we need to find the middle value from our string turned array and remove it
const middle = Math.floor(arr.length / 2);
// We check to make sure that we have more than 2 items in the array so we don't just remove whats there (if there's only one or less items),
//We just return those items.
if (arr.length > 2) {
// We use Splice to remove the middle index.
arr.splice(middle, 1)
//Then use .join() to turn our array back into a string
return arr.join(" ");
} else {
return arr.join(" ");
}
}
console.log(midRemover(name1));
console.log(midRemover(name2));
console.log(midRemover(name3));
console.log(midRemover(name4));
A slightly different approach using RegExp to filter whitespaces and filter to exclude middle indexes.
const foo = str => str
.split(/\s/ig)
.filter((a,b,c) => b == 0 || b === c.length - 1)
.join(' ');
// test
console.log([
"John James",
"Jake Connor Steve",
"George",
"Michael James Jackson"
].map(foo));