Javascript match multiple occurrences in a string? - javascript

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);
});

Related

Javascript Regex: exclude result if preceded by href="

I'm struggling to get a string replaced in Javascript by a regex matching pattern.
I want to replace all matches of {{$myparam}} to be surrounded by a span tag.
This works (see code below). But I want to prevent replacements when a match is preceded by href=".
Example: href="{{$myparam}} must NOT be replaced.
{{$myparam}} MUST be replaced.
myparam can be any text string.
var highlighted = html.replace(/(\{\{(.*?)\}\})/g, function highlight(x) {
return "<span class='highlight'>" + x + "</span>";
});
I've checked out numerous examples in other threads, but I cannot find a solution that works for my case.
You could use
var subject = 'href="{{$myparam}}" or any other {{$myparam}}';
var regex = /"[^"]*"|(\{\{(.*?)\}\})/g;
replaced = subject.replace(regex, function(m, group1) {
if (typeof group1 == 'undefined') return m;
else return "<span class='highlight'>" + group1 + "</span>";
});
alert(replaced);
# href="{{$myparam}}" or any other <span class='highlight'>{{$myparam}}</span>
See a demo on regex101.com.
The idea here is to check for
not_interesting|not_interesting_either|(very_interesting)
and check for the presence of a captured group. You can put anything not interesting to the left as in this example: "[^"]*" (that is anything between double quotes).
If you want to read more on the subject, have a look here.
This seems a bit simpler, just make the href part optional:
mystring = 'this has {{$param1}} and {{$param2}} and href="{{$param3}}" too';
console.log(mystring
.replace(/(href=.)?\{\{([^{} ]+)\}\}/g,
function (match,chk,param) {
return "undefined" !== typeof(chk)
? match
: '<span class="highlight">' + param + '</span>';
}));
The second argument to the callback function is the 'check' part, and the third argument is the captured parameter name. Since the check part is optional and it's fairly precise, it'll only be defined at all if it's 'href="'.
Output, with newlines added for readability:
this has <span class="highlight">$param1</span>
and <span class="highlight">$param2</span>
and href="{{$param3}}" too

str.replace does not replace the $1

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.

Javascript Replace Certain Characters of href after the last slash /

I have this a tag
<a id="Link" href="mysite.net/K&N abc 123.html">Link</a>
I need to use JavaScript to remove non alphanumeric characters then replace spaces with a dash - and lowercase the result.
So everything after /K&N abc 123.html and leave the rest of the href untouched.
The final result would look like this
<a id="Link" href="mysite.com/kn-abc-123.html">Link</a>
I have some code to start but not quite getting it put together right to give the correct result.
var str = document.getElementById("Link").getAttribute("href");
str = str.replace(/\W+/g, '-').toLowerCase();
document.getElementById('Link').setAttribute("href",str);
Here's a bin.
https://jsbin.com/gojoseduji/3/edit?html,output
var href = document.getElementById("Link").getAttribute('href');
var str = href
// replace each block of whitespace with a single '-' character
.replace(/\s+/g, '-')
// Filter out non alphanumerics, excluding : / -
.replace(/[^\:\/\-\w\s.]+/g, "")
// get rid of any hyphens that follow a slash
.replace(/\/-/g, '/')
.toLowerCase();
I just used the whitespace identifier, and make sure to make it global :)
EDIT: Added the condition to strip all non alpha-numerics except [/ - :]. I stripped the whitespace first and had the second regex ignore the hypens. I also made the variable names different, as your original code modified the variable. Just my preference.
EDIT-AGAINN: This original way was nice, but now there's a few different regEx's, maybe someone with smoother regex skills can condense those down and make a better answer?
try this
var str = document.getElementById("Link").getAttribute("href");
var lastitem = str.split("/").pop(); //taking out last item after slash
lastitem = lastitem.split( " " ).map( function(value){ return value.replace(/[*\(\)&/]/g, '').toLowerCase() } ).join( "-" ); //removing special characters and replacing space with hyphen
str = str.substring(0, str.lastIndexOf("/")) + lastitem;
document.getElementById('Link').setAttribute("href",str);
You can use replace with a callback:
var href = document.getElementById("Link").getAttribute('href');
href = href.replace(/^((?:.*?\/{2})?[^\/]*\/)(.+)$/, function($0, $1, $2) {
return $1 + $2.replace(/[^\w\s.]+/g, '').replace(/\s+/g, '-').toLowerCase(); });
document.getElementById('Link').setAttribute("href", href);
//=> mysite.net/kn-abc-123.html
Or with ftp:// in URL:
str = 'ftp://mysite.net/K&N abc 123.html'
str = str.replace(/^((?:.*?\/{2})?[^\/]*\/)(.+)$/, function($0, $1, $2) {
return $1 + $2.replace(/[^\w\s.]+/g, '').replace(/\s+/g, '-').toLowerCase(); });
//=> ftp://mysite.net/kn-abc-123.html

Find and replace using array of keys to find, and array values to replace

I have, in jQuery, written the below:
$(document).ready(function() {
var wordlist = new Array();
wordlist['BioResource'] = 'Bio Resource is a lorem';
var array_length = wordlist.length;
for(var key in wordlist) {
$("p").html(function(index, value) {
return value.replace(new RegExp("\b(" + key + ")\b", "gi"), '$1');
});
}
});
It should (but doesn't), loop through the wordlist array and for each key, try to find that word in any paragraph tags and replace it with itself but wrapped in an anchor with a title tag of the appropriate value of the array at that key.
What am I doing wrong?
The regex itself is working if I remove the array aspect from this and directly input the key and value like this:
return value.replace(/\b(BioResource)\b/gi, '$1');
Thanks in advance for your help.
Paul
Change this:
"\b(" + key + ")\b"
To this:
"\\b(" + key + ")\\b"
\b in string literal represents backspace character. Even if it doesn't have any special meaning, to specify \ in string, you need to escape it: \\. Otherwise, \ will just vaporize, or a syntax error will be thrown.
You could turn it around and replace any word you can find. This way you only iterate over each paragraph text once to perform the actual replacement.
This solution finds all words inside each paragraph, using (\w+) and see whether the contents matches in your wordlist object. When found it makes the replacement, if not, it will leave that word alone.
$('p').html(function(index, old) {
return old.replace(/(\w+)/g, function($0, $1) {
return wordlist[$1] || $0;
});
});

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