Created
December 6, 2020 18:05
-
-
Save nikola-wd/b10b85545da9afe4d9a29466eeae30b7 to your computer and use it in GitHub Desktop.
[case-insensitive preg replace all] Replace all substr occurencies no matter the case ("str", <mark>str</mark> #javascript
This file contains 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
function matchCase(text, pattern, tag = '') { | |
var result = ''; | |
for(var i = 0; i < text.length; i++) { | |
var c = text.charAt(i); | |
var p = pattern.charCodeAt(i); | |
if(p >= 65 && p < 65 + 26) { | |
result += c.toUpperCase(); | |
} else { | |
result += c.toLowerCase(); | |
} | |
} | |
let finalResult = result; | |
if (tag) { | |
finalResult = `<${tag}>${result}</${tag}>`; | |
} | |
return finalResult; | |
} | |
const searchQuery = 'velit'; | |
const r = new RegExp( "(" + searchQuery + ")" , 'gi' ); | |
const yo = "asd velitasd Velit asd".replace(r, function(match) { | |
return matchCase(searchQuery, match, 'mark'); | |
}); | |
console.log(yo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment