I am trying to generate keywords to search and display some content from the database.I have given a sample search text and keywords that I would like to derive from the keyword. Can someone guide me on how to implement the logic to get the keywords from a dynamic search string as shown below?
var searchText='My name is John santose mayer'
var Keywords={
1: 'My name is John santose mayer',
2: 'My name is johns santose',
3: 'My name is John',
4: 'My name is',
5: 'My name'
6: 'My'
}
const keywords = searchText.split(' ');
const phrases = [];
for(let length = keywords.length; length > 0; length--) {
phrases.push(keywords.slice(0, length).join(' '));
}
Something like this using reduce
?
var searchText='My name is John santose mayer'; let keywords = searchText.split(' ').reduce((prev, next) => { const concatWith = prev[prev.length - 1]? prev[prev.length - 1] + ' ': '' return [...prev, concatWith + next] }, []).reverse() console.log(keywords)
Simple combination of split
, map
, slice
and reduce
should do the trick.
const foo = "My name is John santose mayer"
.split(" ")
.map<string>((_, i, arr) => arr.slice(0, arr.length - i).join(" "))
// [
// "My name is John santose mayer",
// "My name is John santose",
// "My name is John",
// "My name is",
// "My name",
// "My"
// ]
.reduce<{ [key: number]: string }>((acc, curr, i) => {
acc[i + 1] = curr;
return acc;
}, {});
console.log(foo);
// {
// "1": "My name is John santose mayer",
// "2": "My name is John santose",
// "3": "My name is John",
// "4": "My name is",
// "5": "My name",
// "6": "My"
// }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.