str.replace does not replace the $1 - javascript

I'm trying to make a little highlight function.
The Problem i have is, that i does not insert the matched into the $1.
My function looks like
getMatch(str, search) {
let result = str.replace(new RegExp(search, 'gi'), '<span class="match">$1</span>');
return result;
}
as you can see, it should wrap the match. but it does not.
here an example how i use it:
let string = 'My string with higlighting.';
let match = getMatch(string, 'With');
my expected result is:
My string <span class="match">with</span> highlighting.
but i just get:
My string <span class="match">$1</span> highlighting.
so the $1 was not replaced by the matching.
How can i solve that?

Your 'With' has no capturing groups, thus, $1 is parsed as a literal string.
If you want to wrap the whole match with span, replace $1 with $&.
getMatch(str, search) {
let result = str.replace(new RegExp(search, 'gi'), '<span class="match">$&</span>');
return result;
}
See MDN replace reference:
$& Inserts the matched substring.

The with is not a capturing group, you should transform it by adding parenthesis :
let string = 'My string with higlighting.';
let match = getMatch(string, '(With)');
Output will be:
My string <span class="match">with</span> higlighting.

Related

Need to replace a string from a long string in javascript

I have a long string
Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
removable_str2 = 'ab#xyz.com;';
I need to have a replaced string which will have
resultant Final string should look like,
cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
I tried with
str3 = Full_str1.replace(new RegExp('(^|\\b)' +removable_str2, 'g'),"");
but it resulted in
cab#xyz.com;c-c.c_ab#xyz.com;
Here a soluce using two separated regex for each case :
the str to remove is at the start of the string
the str to remove is inside or at the end of the string
PS :
I couldn't perform it in one regex, because it would remove an extra ; in case of matching the string to remove inside of the global string.
const originalStr = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;ab#xyz.com;c_ab#xyz.com;';
const toRemove = 'ab#xyz.com;';
const epuredStr = originalStr
.replace(new RegExp(`^${toRemove}`, 'g'), '')
.replace(new RegExp(`;${toRemove}`, 'g'), ';');
console.log(epuredStr);
First, the dynamic part must be escaped, else, . will match any char but a line break char, and will match ab#xyz§com;, too.
Next, you need to match this only at the start of the string or after ;. So, you may use
var Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
var removable_str2 = 'ab#xyz.com;';
var rx = new RegExp("(^|;)" + removable_str2.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "g");
console.log(Full_str1.replace(rx, "$1"));
// => cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
Replace "g" with "gi" for case insensitive matching.
See the regex demo. Note that (^|;) matches and captures into Group 1 start of string location (empty string) or ; and $1 in the replacement pattern restores this char in the result.
NOTE: If the pattern is known beforehand and you only want to handle ab#xyz.com; pattern, use a regex literal without escaping, Full_str1.replace(/(^|;)ab#xyz\.com;/g, "$1").
i don't find any particular description why you haven't tried like this it will give you desired result cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
const full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
const removable_str2 = 'ab#xyz.com;';
const result= full_str1.replace(removable_str2 , "");
console.log(result);

Regex remove underscores from a given string

I try to transform string using String replace method and regular expression. How can I remove underscores in a given string?
let string = 'court_order_state'
string = string.replace(/_([a-z])/g, (_, match) => match.toUpperCase())
console.log(string)
Expected result:
COURT ORDER STATE
You could use JavaScript replace function, passing as input:
/_/g as searchvalue parameter (the g modifier is used to perform a global match, i.e. find all matches rather than stopping after the first one);
(blank space) as newvalue parameter.
let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);
In your code you could match either and underscore or the start of the string (?:_|^) to also match the first word and match 1+ times a-z using a quantifier [a-z]+
Then append a space after each call toUpperCase.
let string = 'court_order_state';
string = string.replace(/(?:_|^)([a-z]+)/g, (m, g1) => g1.toUpperCase() + " ");
console.log(string)
let string = 'court_order_____state'
string = string.replace(/_+/g, ' ').toUpperCase()
console.log(string)
It can be as simple as the below:
let string = 'court_order_state'
string = string.replace(/_/g, ' ').toUpperCase();
console.log(string);
Here the 'g' represents global, whereas the '/' is surrounded by what we're looking for.
Instead of matching the first character just after every _ and making them uppercase (from the regex that you have used), you can simply convert the entire string to uppercase, and replace the _ with space by the following:
let string = 'court_order_state';
string = string.toUpperCase().replace(/_+/g, " ");
console.log(string);

Javascript match multiple occurrences in a string?

So my current HTML looks like
<p class="comment-post-text">#333<br /> #44<br />#564</p>
I'm trying to create links that looks like
#333 #44 #564
However my result is
#333 #333 #333
and I'm using Regex to verify that if a number comes after the # symbol, transform the text into a link and link-back to the hash of the next post. It's a quoting system more or less. My problem is that it seems to only be matching the first occurrence of my regex, rather than matching for each occurrence.
$('.comment-post-text').each(function( index ) {
let text = $( this ).text();
let matches = text.match(/#(\d+)/);
if(matches !== null){
console.log(matches);
let newText = replaceAll(text, /#(\d+)/, "<a href = '#pi_" + matches[1] + "'>" + matches[0] + "</a><br/>");
$(this).replaceWith(newText);
}
});
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
The problem is occurrence here at matches[1] it's only capturing the first occurrence of the pattern so looping through the matches array would be useless. Is there a way to have the matches array hold each occurrence of the match? Any help greatly appreciated.
You don't need to use the String.prototype.match method to check if there is something to replace. Use the String.prototype.replace method directly with a backreference for the first capturing group $1 and the whole match $& in the replacement string.
$('.comment-post-text').each(function( index ) {
let text = $( this ).text();
let newText = text.replace(/#(\d+)/g, "<a href = '#pi_$1'>$&</a><br/>");
$(this).replaceWith(newText);
});

Replace partial matching string with bold string

I would like to replace matched parts of a string by bold strings.
const str = 'This is an Example';
const term = 'exam';
Now I would like to get the result
This is an <strong>Exam</strong>ple
I tried to use an regEx, but this seams to have a wrong syntax and also with this the uppercase of Example would be ignored:
const result = str.replace(new RegExp(escapeRegExp(term), 'g'), '<strong>' + term + '</strong>');
If you want to capture with case insensitivity you need to include the i flag. Also, if you want to preserve the original case rather than replacing it with the case of term, you can use a capture group as follows:
const str = 'This is an Example';
const term = 'exam';
const result = str.replace(new RegExp(`(${term})`, 'gi'), '<strong>$1</strong>');
console.log(result);
Add i flag on expression:
Perform case-insensitive matching
new RegExp(term, 'gi')

Replace a substring with javascript

Need to replace a substring in URL (technically just a string) with javascript.
The string like
http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE
or
http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest
means, the word to replace can be either at the most end of the URL or in the middle of it.
I am trying to cover these with the following:
var newWord = NEW_SEARCH_TERM;
var str = 'http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest';
var regex = /^\S+SearchableText=(.*)&?\S*$/;
str = str.replace(regex, newWord);
But no matter what I do I get str = NEW_SEARCH_TERM. Moreover the regular expression when I try it in RegExhibit, selects the word to replace and everything that follows it that is not what I want.
How can I write a universal expression to cover both cases and make the correct string be saved in the variable?
str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)
The \S+ and \S* in your regex match all non-whitespace characters.
You probably want to remove them and the anchors.
http://jsfiddle.net/mplungjan/ZGbsY/
ClyFish did it while I was fiddling
var url1="http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE";
var url2 ="http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest"
var newWord = "foo";
function replaceSearch(str,newWord) {
var regex = /SearchableText=[^&]*/;
return str.replace(regex, "SearchableText="+newWord);
}
document.write(replaceSearch(url1,newWord))
document.write('<hr>');
document.write(replaceSearch(url2,newWord))

Categories