Last active
January 3, 2022 13:40
-
-
Save 0xSG/c85c0dc4976657e1989c94963ddcf677 to your computer and use it in GitHub Desktop.
Sub string around a keyword in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns a sub-string with the specified keyword in the middle. | |
* @param text: Full statement with the keyword in it. | |
* @param keyword: Keyword which you want to concentrate. | |
* @param subStringLen: The length of the desired resultant string. | |
* @param truncate: If true it will add '...' at the starting and ending of the resultant string. | |
* @author sooryagangaraj | |
* @return string | |
*/ | |
function subStringAroundKeyword(text, keyword, subStringLen, truncate = true) { | |
// Total chars in text | |
const totalTextLen = text.length; | |
// Number of chars needed around keyword | |
var charsAroundNeeded = subStringLen - keyword.length | |
// Starting and ending index for adjusting | |
var startingIndex = text.toLowerCase().indexOf(keyword.toLowerCase()) | |
var endingIndex = startingIndex + keyword.length | |
if (startingIndex === -1) return "" | |
while (charsAroundNeeded > 0) { | |
var indexChanged = false | |
// Adjusting starting index | |
if (startingIndex - 1 >= 0) { | |
startingIndex -= 1 | |
charsAroundNeeded -= 1 | |
indexChanged = true | |
} | |
// Adjusting ending index | |
if (endingIndex + 1 < totalTextLen && charsAroundNeeded > 0) { | |
endingIndex += 1 | |
charsAroundNeeded -= 1 | |
indexChanged = true | |
} | |
// Reducing chars if there is nothing to get adjusted | |
if (!indexChanged) { | |
charsAroundNeeded -= 1 | |
} | |
} | |
// Checking if we can avoid three dots at the end if the keyword is within three positions from last | |
let endingToTotalTextLen = totalTextLen - endingIndex; | |
let isEndingToTotalTextLenWithin3 = endingToTotalTextLen > 0 && endingToTotalTextLen <= 3; | |
if (isEndingToTotalTextLenWithin3) endingIndex = totalTextLen; | |
// Checking if we can avoid three dots at the beginning if the keyword starts withing three positions from start | |
let isStartingIndexWithing3 = startingIndex > 0 && startingIndex <= 3; | |
if (isStartingIndexWithing3) startingIndex = 0; | |
// Substring with keyword and around text. | |
let resultingSubString = ((truncate && startingIndex > 0) ? "..." : "") | |
+ text.slice(startingIndex, endingIndex) | |
+ ((truncate && endingIndex < totalTextLen) ? "..." : ""); | |
return resultingSubString | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment