I am learning JavaScript , the fundamentals for now and what I don’t get, is how to count the characters in the string in order to use the slice on the certain string and extract a certain word out of the string. For example
let text = “JavaScript”, “apples”, “avocado”);
let newText = text.slice(?),(?);
How do I know or count the position of apples for example or JavaScript? Thank you!
CodePudding user response:
Try like this:
let text = "JavaScript, apples, avocado";
let newText = text.slice(text.indexOf("JavaScript"));
let newText2 = text.slice(text.indexOf("apples"));
console.log(newText)
console.log(newText2)
CodePudding user response:
split
the string into an array, filter
out the item you don't want, and then splice
in the string you do want. Finally, join
the array elements into a new string.
const str = 'JavaScript, apples, avocado';
function replace(str, search, replacement) {
// Create an array using `split`
const arr = str.split(', ');
// Find the index of the item you're looking for
const index = arr.findIndex(el => el === search);
// `filter` out the element you don't want
const newArr = arr.filter(el => el !== search);
// `splice` in the new replacement string
newArr.splice(index, 0, replacement);
// Return the new string
return newArr.join(', ');
}
console.log(replace(str, 'apples', 'biscuit'));
CodePudding user response:
Few observations/suggestions :
- String will always wrapped with the quotes but in your post it is not looks like a string.
- Why you want to slice to get the word from that string ? You can convert that string into an array and then get that word.
Implementation steps :
- Split string and convert that in an array using String.split() method.
- Now we can find for the word you want to search from an array using Array.find() method.
Working Demo :
// Input string
const text = "JavaScript, apples, avocado";
const searchText = 'apples';
// Split string and convert that in an array using String.split() method.
const splittedStringArray = text.split(',');
// Now we can find for the word from splittedStringArray using Array.find() method.
const result = splittedStringArray.find(item => item.trim() === searchText);
// Output
console.log(result);