Case insensitive search with case sensitive replace - javascript

I have a simple regex search and replace function and was wondering if there is a good way to go a case sensitive replace on a case insensitive search? Example below:
function filter(searchTerm) {
var searchPattern = new RegExp(searchTerm, 'ig');
....
textToCheck = textToCheck.replace(searchPattern, '<span class="searchMatchTitle">' + searchTerm + '</span>');
The search term at the top of the function could have a capitol in it and I wanted to make it match any string with upper or lower in it, hence the 'i' flag.
I end up with weird results when doing the replace as it takes the original seach string (which could be any mix) and uses that a replacement where there might be different formatting.
Id really love to preserve the original formatting and add the span around it. Is my approach the best way? If it is, can you use groups in the same way you can in Perl? e.g.
s/ \(=\+\) /\1/g
My attempts using similar types of syntax and examples form the web only result in literal string replace

function filter(searchTerm) {
var searchPattern = new RegExp('('+searchTerm+')', 'ig');
....
textToCheck = textToCheck.replace(searchPattern, '<span class="searchMatchTitle">$1</span>');
...
}

You can use groups, but the syntax is slightly different. Try something like this:
var str = 'this is a dog eat Dog eat DOG world'
str = str.replace(/(dog)/gi, '<span>$1</span>')
// str is now: "this is a <span>dog</span> eat <span>Dog</span> eat <span>DOG</span> world"

Related

How do I replace all emails in string with the same email formatted in JavaScript [duplicate]

I have a string in JavaScript in which I'd like to find all matches of a given phrase and wrap them with a tag. I haven't been able to find the right regex method here to replace a case insensitive phrase and replace it with itself with additional text around it. For example:
Input string:
"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."
Case insensitive phrase: "cat"
Output string:
"I like to play with <em>cat</em>s, as does <em>Cat</em>hy, who is a member of A<em>CAT</em>A, which is the American <em>Cat</em> And Tiger Association."
So, basically, inject <em></em> around any matches. I can't just do a straight-up replace, because I'll lose the original case in the input string.
You could use:
"Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");
Which will return:
"Foo bar <em>cat</em>"
You can do straight-up replace by using a replace function:
str.replace(/cat/ig, function replace(match) {
return '<em>' + match + '</em>';
});
One needs no capturing group around the whole regex because there is a $& placeholder that refers to the whole match from the string replacement pattern:
"Foo bar cat".replace(/cat/ig, "<em>$&</em>");
^^
See the Specifying a string as a parameter section:
$& Inserts the matched substring.
Thus, no need of any callback methods or redundant regex constructs.
You can solve it very simple, just use a capturing group with the word you want, and then use the replacement string <em>$1</em>. You can use a regex like this:
(cat)
working demo
Below, you can see in green the matches (capturing the word cat insensitively) and in the substitution section you can see the replacements.
You can use this code:
var re = /(cat)/ig;
var str = '"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."\n';
var subst = '<em>$1</em>';
var result = str.replace(re, subst);

Regex conditional search javascript [duplicate]

I have a string in JavaScript in which I'd like to find all matches of a given phrase and wrap them with a tag. I haven't been able to find the right regex method here to replace a case insensitive phrase and replace it with itself with additional text around it. For example:
Input string:
"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."
Case insensitive phrase: "cat"
Output string:
"I like to play with <em>cat</em>s, as does <em>Cat</em>hy, who is a member of A<em>CAT</em>A, which is the American <em>Cat</em> And Tiger Association."
So, basically, inject <em></em> around any matches. I can't just do a straight-up replace, because I'll lose the original case in the input string.
You could use:
"Foo bar cat".replace(/(cat)/ig, "<em>$1</em>");
Which will return:
"Foo bar <em>cat</em>"
You can do straight-up replace by using a replace function:
str.replace(/cat/ig, function replace(match) {
return '<em>' + match + '</em>';
});
One needs no capturing group around the whole regex because there is a $& placeholder that refers to the whole match from the string replacement pattern:
"Foo bar cat".replace(/cat/ig, "<em>$&</em>");
^^
See the Specifying a string as a parameter section:
$& Inserts the matched substring.
Thus, no need of any callback methods or redundant regex constructs.
You can solve it very simple, just use a capturing group with the word you want, and then use the replacement string <em>$1</em>. You can use a regex like this:
(cat)
working demo
Below, you can see in green the matches (capturing the word cat insensitively) and in the substitution section you can see the replacements.
You can use this code:
var re = /(cat)/ig;
var str = '"I like to play with cats, as does Cathy, who is a member of ACATA, which is the American Cat And Tiger Association."\n';
var subst = '<em>$1</em>';
var result = str.replace(re, subst);

In JavaScript how do I get all matches using regex instead of the last one

I'm struggling to figure out how to get this regex to work without needing a loop. Here's the code that works:
var template = {name: "Oscar", anotherName: "your twin", hello: 'world'}
var str = "Hello, {{name}} I'm {{anotherName}}. Hello to the {{hello}}"
Object.keys(template).forEach(function (keyName) {
pattern = new RegExp('{{' + keyName + '}}', 'g');
str = str.replace(pattern, template[keyName]);
})
// => str "Hello, Oscar I'm your twin. Hello to the world"
The thing about this code I don't like is that it's in a loop generating regex when I feel like a regex should be able to handle this use case. However, my regex is always only matching the last item. I was doing regex like str.match(/({{.}})/gi) but then only the {{hello}} was getting matched.
Preferably I'd like to do something where I can get all matches in an array and then map the array like matchesFromRegex.map(match => template[match]).join('')
Also, I'm in an vanilla JS environment so .matchAll (which isn't supported in IE) wouldn't work.
In a RegExp string, { has a special meaning (it lets you set a cardinality for a match, like \d{5} for five digits).
Use new RegExp('\\{\\{' + keyName + '}}', 'g'); instead. The double backslash in JavaScript will create a backslash, which will escape the { character.
If you want to avoid the loop, you can use the function-based version of replace instead:
const pattern = /\{\{([^}]*)}}/g;
str.replace(pattern, (_, key) => template[key]);
To break it down, pattern has a capture group (the parts in ()). The String.prototype.replace function can let you supply a function for doing replacements, which will be passed your match results.

jQuery - find and replace substring

Let's say I got strings like this
'Hello, I am ***Groot*** today.'
'This is ***not*** my final form.'
'Test test ***123***'
and I want to add some new stuff before the first and after the second asterix to make it look like
'Hello, I am FIRST***Groot***LAST today.'
'This is FIRST***not***LAST my final form.'
'Test test FIRST***123***LAST'
So far I managed to get this
var first = jQuery(this).html().indexOf("***");
var last = jQuery(this).html().lastIndexOf("***");
console.log( jQuery(this).html().substring(first, last+3) );
but I fail on the replacement...so close, yet so far....
You can use regex pretty easily... this will work for all of your strings.
JSFiddle (check js console)
var str = jQuery(this).text();
str = str.replace(/(\*{3}.*\*{3})/, "FIRST$1LAST");
console.log(str);
Also, you don't really need to create the jQuery objects just to get the text, could just do this:
var str = this.innerText;
str = str.replace(/\*{3}.*\*{3}/, "FIRST$&LAST");
console.log(str);
I believe the correct special replacement character in your replacement parameter should be $& rather than $1 just for readability sake and best practices.
$& corresponds to the matched substring, whereas $1 makes it seem like there are multiple matches in the RegExp object.
Reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

myString.replace( VARIABLE, "") ...... but globally

How can I use a variable to remove all instances of a substring from a string?
(to remove, I'm thinking the best way is to replace, with nothing, globally... right?)
if I have these 2 strings,
myString = "This sentence is an example sentence."
oldWord = " sentence"
then something like this
myString.replace(oldWord, "");
only replaces the first instance of the variable in the string.
but if I add the global g like this myString.replace(/oldWord/g, ""); it doesn't work, because it thinks oldWord, in this case, is the substring, not a variable. How can I do this with the variable?
Well, you can use this:
var reg = new RegExp(oldWord, "g");
myString.replace(reg, "");
or simply:
myString.replace(new RegExp(oldWord, "g"), "");
You have to use the constructor rather than the literal syntax when passing variables. Stick with the literal syntax for literal strings to avoid confusing escape syntax.
var oldWordRegEx = new RegExp(oldWord,'g');
myString.replace(oldWordRegEx,"");
No need to use a regular expression here: split the string around matches of the substring you want to remove, then join the remaining parts together:
myString.split(oldWord).join('')
In the OP's example:
var myString = "This sentence is an example sentence.";
var oldWord = " sentence";
console.log(myString.split(oldWord).join(''));
According to the docs at MDN, you can do this:
var re = /apples/gi;
var str = 'Apples are round, and apples are juicy.';
var newstr = str.replace(re, 'oranges');
console.log(newstr); // oranges are round, and oranges are juicy.
where /gi tells it to do a global replace, ignoring case.

Categories

Resources