Search කරපු text එකක් JS වලින් bold කරලා පෙන්වන්නේ කොහොමද?

Google එකේ, සහ තවත් වෙබ් සයිට්වල search එකේ අපි දෙයක් ටයිප් කළාම එන resultsවල අපි ටයිප් කරපු දේ highlight කරලා පෙන්වන හැටි දැකලා ඇති​නේ. ඒක කරන්නේ කොහොමද කියලා කල්පනා කළා නම්, ඒ ප්‍රශ්නෙම උත්තරේ තියෙනවා.

JavaScriptවල includes() එකෙන් String එකක අපි දෙන text එකක් තියෙනවද කියන එක boolean එකක් විදියට දුන්නට මේ වැඩේදි අපිට ඕන වෙන්නෙ search() function එක. ඒකෙන් ලැබෙන්නෙ search කරපු text එකේ index එක!

const article = "Sri Lankans love JavaScript for its flexibility, power, and the ability to build scalable web applications."

const searchInput = "Lankans"

console.log(article.search(searchInput)) // අපිට මෙතනදි index එක 4 කියලා ලැබෙනවා
Advertisement

ඔන්න දැන් පටන් ගැන තැන දන්නවා. ඉවර වෙන තැන index එක? ඒක අපි දැනටමත් දන්න searchInput එකෙන් ගන්න පුළුවන්!

const from = article.search(searchInput)

const to = from + searchInput.length

දැන් ඉතින් තියෙන්නේ original text එකේ search කරපු text එක bold කරන්න.

article.slice(from, to).replace(searchInput, `<b>${searchInput}</b>`)

මේකෙන් අපිට <b>Lankans</b> කියලා ලැබෙනවා.

සාමාන්‍යයෙන් කසන හැඟීමක් තියෙන මං වගේ එකෙක්ට ඔහොම කරලා මදි. Google එකේ search resultsවල description එකේ තව කොටසක් (context එකක්) එක්ක තමයි මේ bold text එක පේන්නේ. අන්න ඒක කරගන්න පුළුවන් contextSize එකක් දාගත්තාම. ඒවත් එක්ක negative numbersනුත් handle කරපු code එක පහළින්:

const contextSize = 20

const startIndex = article.search(searchInput)

const ensurePositiveNumber = input => input < 0 ? 0 : input

const from = ensurePositiveNumber(startIndex - contextSize)

const to = startIndex + searchInput.length + contextSize

const result = (`...${article.slice(from, to).trim()}...`).replace(searchInput, `<b>${searchInput}</b>`)

මේකන් ලැබෙනවා මෙහෙම: “…Sri <b>Lankans</b> love JavaScript for its…”

දැන් වැඩේ හරි!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You cannot copy content of this page