Created
April 30, 2016 21:16
-
-
Save calibr/6ca522e9d688183b5a42dc4b58978a9b to your computer and use it in GitHub Desktop.
Make all occurrences of specific string bold
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
| // has been got from http://stackoverflow.com/a/3410557/3097116 | |
| function getIndicesOf(searchStr, str, caseSensitive) { | |
| var startIndex = 0, searchStrLen = searchStr.length; | |
| var index, indices = []; | |
| if (!caseSensitive) { | |
| str = str.toLowerCase(); | |
| searchStr = searchStr.toLowerCase(); | |
| } | |
| while ((index = str.indexOf(searchStr, startIndex)) > -1) { | |
| indices.push(index); | |
| startIndex = index + searchStrLen; | |
| } | |
| return indices; | |
| } | |
| function bolderify(query, suggestion) { | |
| var indices = getIndicesOf(query, suggestion, false); | |
| var resultDiv = document.createElement("div"); | |
| var currentText = ""; | |
| for(var i = 0; i < suggestion.length;) { | |
| if(indices.indexOf(i) !== -1) { | |
| if(currentText) { | |
| var span = document.createElement("span"); | |
| span.textContent = currentText; | |
| resultDiv.appendChild(span); | |
| currentText = ""; | |
| } | |
| var bolder = document.createElement("b"); | |
| bolder.textContent = suggestion.substr(i, query.length); | |
| resultDiv.appendChild(bolder); | |
| i += query.length; | |
| } | |
| else { | |
| currentText += suggestion[i]; | |
| i++; | |
| } | |
| } | |
| if(currentText) { | |
| var span = document.createElement("span"); | |
| span.textContent = currentText; | |
| resultDiv.appendChild(span); | |
| } | |
| return resultDiv; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment