replace a pattern with URL - javascript

The idea is taken from here
I have the following code:
myApp.filter('parseUrlFilter', function () {
var urlPattern = /^E\d{5}-\d{2}$/;
return function (text, target) {
return text.replace(urlPattern, '<a target="' + target + '" href="http://somepage.com?number=$&">$&</a>') + " | ";
};
});
I'm still trying to understand how this code exactly works but it does not convert the text to URL.
Like E12345-01 does not become somepage.com?number=E12345-01
I think I'm missing something about how the regex works here. Any help will be appreciated.
Edit: added plnkr with somewhat working answer of machinehead115

Without seeing you HTML code I assume that you are actually binding / using the filter there, like so:
<div ng-bind-html="'E12345-01' | parseUrlFilter:'_blank'"></div>
In order to have the filter actually output the link text as code you need to include $sce as a dependency of filter and return the link using $sce.trustAsHtml(link):
angular.module('app', [])
.filter('parseUrlFilter', function($sce) {
var urlPattern = /^E\d{5}-\d{2}$/;
return function(text, target) {
return $sce.trustAsHtml(text.replace(urlPattern, '<a target="' + target + '" href="http://somepage.com?number=$&">$&</a>') + ' | ');
};
});
Here is an example plnk of the code working.

I'm not sure I understand your question, nor your context. My assumption is that you need to extract the number from an incomingString and use that number to generate a new link string. Given those requirements, the below would get you going...
//this var represents the string that would hold the identifier you're interested in
var originString = "blah blah blah E12345-01 more blah blah blah";
function DoIt(incomingString)
{
//create a regex pattern
var urlPattern = new RegExp(/E\d{5}-\d{2}/);
//get the match
var theMatch = urlPattern.exec(incomingString);
//add the match to your new url
var returnString = "www.whateversite.com/number=" + theMatch;
//from here you can do whatever you want with that string
//for now, I'll just return it as is...
return returnString;
}
console.log(DoIt(originString));

here is the working regex for you
([E]\d{5}-\d{2})
check here https://regex101.com/r/O6YFlj/1

The problem is not in your URL matching and replacement code. I extracted the following from your code and used it. Worked perfect:
<script>
var urlPattern = /^E\d{5}-\d{2}$/;
var text = "E12345-01";
document.write(text.replace(urlPattern, '$&') + " | ");
</script>
The issue must be with the value of text. use console.log(text) to see whether you're getting the right value in your variable or not.

Related

Javascript - Get substring that comes after "string1" and before "string2"

When making a fetch to a certain URL, I am getting an HTML page in the format of text as I wanted.
Inside of it, there are plenty of id=(...)" and I require one of them
So I am asking, how could I get an array with all the strings that come after "id=" and before the " " "?
I made some tries such as :
var startsWith = "id="
var endsWith = "\""
var between = fullString.slice(fullString.indexOf(startsWith), fullstring.indexOf(endsWith))
but couldn't get it to work.
Any suggestions are welcome
you can use the following regex: /id=\"(.*?)\"/gmi.
The code will be as such:
fullString.match(/id=\"(.*?)\"/gmi)
The result will be an array of id="your id"
and then you can do the following:
var between = fullString.match(/id=\"(.*?)\"/gmi).map(str => str.substr(str.indexOf('id=\"') + 'id=\"'.length).slice(0, -1))
Why you dont use a plugin like jquery? Please refer to this example:
var fullString = "<y>your cool html</y>";
var $html = $(fullString);
var stuffInside = $(html).find('#yourId');
console.warn('stuffInside:', stuffInside.html());

Replace multiple occurrences of a string (url) in a textarea

Probably I am not able to achieve this because I don't know much about regEx.
I have an array of unique links uniqueLinks.
Whenever those links appear in the HTML code I have my textarea, I want them to be replaced with {{tracking_link_N}} where N stands for the key. Right now I have the following function called when a button is pressed
function detect_links() {
var links = [];
var uniqueLinks = [];
var html = $("textarea[name=html]").val();
// Getting all the links in the textarea to replace them
$(html).find('a').each(function() {
links.push($(this).attr('href'));
})
// Creating an array of unique links uniqueLinks
$.each(links, function(i, el) {
if ($.inArray(el, uniqueLinks) === -1) uniqueLinks.push(el);
});
$.each(uniqueLinks, function(key, value) {
var newHTML = $("textarea[name=html]").val().replace(value, '{{tracking_link' + key + '}}');
$("textarea[name=html]").val(newHTML);
});
}
My textarea is:
<textarea name="html" class="form-control" rows="15"></textarea>
With this code so far it only replaces the first occurrence of the URL in the textarea. In some cases however the same URL appears multiple times in the textarea. E.g.
Google
Google 2
Google 3
My code returns
{{tracking_link0}}
{{tracking_link1}}
Google 3
It should return instead
{{tracking_link0}}
{{tracking_link1}}
{{tracking_link0}}
What I tried reading the other discussions is to change the replace() function like this
replace(/value/g, '{{tracking_link' + key + '}}');
But I don't get any appreciable result.
My URLs contain parameters as well, for example:
http://tracking.testapp.com/affil?offer=105&id=1152
Thanks for any help to address this issue.
PS: explaining the downvotes you give to questions makes them more believable
/value/g means to search for the exact string "value" globally. What you want is for it to search for the value of your value variable globally. For this, you must use RegExp() so that JavaScript parses value to mean the value of the variable value instead of the string "value".
var newHTML = $("textarea[name=html]").val().replace(new RegExp(escapeRegExp(value), "g"), '{{tracking_link' + key + '}}');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Add this somewhere in your JavaScript code (taken from this post):
escapeRegExp = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
Your issue is because the replace() method only works on the first found instance when you provide it a string value. Instead, if you give it a Regular Expression with the Global flag set (g) then it will find and replace all instances of the provided value.
Also note that you can make the code more succinct by passing a function to val(). Try this:
var uniqueLinks = ['http://google.co.uk', 'http://google.com'];
$.each(uniqueLinks, function(key, value) {
var re = new RegExp(value, 'gi');
$("textarea[name=html]").val(function(i, v) {
return v.replace(re, '{{tracking_link' + key + '}}');
});
});
textarea {
width: 100%;
height: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="html">Google
Google 2
Google 3
</textarea>
var uniqueLinks = ['http://google.co.uk', 'http://google.com'],
textArea=$("textarea[name=html]"),
text=textArea.text();
$.each(uniqueLinks, function(key, value) {
var re = new RegExp('"'+value+'">([^<]*)</',"g");
text=text.replace(re,'"'+value+'">{{tracking_link'+key+'}}<');
});
console.log(text);
textArea.text(text);
textarea {
width: 100%;
height: 80px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="html">Google
Google 2
Google 3
</textarea>
This replace the text inside the links

Finding Text with array and replace with link around text with a class equal to text

So using jQuery, I'm trying to use an array to search through paragraph elements using an array and when it finds certain words it converts that word to a link with that class.
I'm trying to use this:
jQuery('.story').html(function(i,html) {
var w = ['ocean','waves','bed', 'swimming'];
$.each(w,function(i,w) {
html = html.replace(new RegExp('' + w + '', 'g'),w[i]);
});
return html;
});
jsfiddle
The end result would turn ocean into ocean et al.
But it doesn't seem to be working. I don't really understand why either. Thanks ahead of time.
m(_ _)m
_|7O
(The end plan is to have it so that those words play certain SFX when pressed and I'm basing off the class so when the word shows up again in the story it plays the same sound).
Like this?
var w = ['ocean','waves','bed', 'swimming'],
reg = new RegExp('(' + w.join('|') + ')','g');
jQuery('.story').html(function(_, curHtml) {
return curHtml.replace(reg,"<a href='#' class='$1'>$1</a>");
});
Demo
You need to use html instead of val and construct the regexp based on all the words so that they can be matched at once and replace the matched value with the string and using the match token, $1
How about?
var arr = ['ocean','waves','bed', 'swimming'];
var result = $('.story').text();
$.each(arr, function (i, val) {
result =
result.replace(val, '' + val + '');
});
$('.story').html(result);
http://jsfiddle.net/8XWf3/21/
There are a few issues with your code:
You use the same variable i and w twice. They override each other. Although that does not make a difference here
You use .val instead of .html. .val should only be used for form fields.
You swapped the reg exp and the replacement in the replace call
Try this:
jQuery('.story').html(function(i,val) {
var w = ['ocean','waves','bed', 'swimming'];
$.each(w, function(j,w) {
val = val.replace(new RegExp(w, 'g'), '' + w + '');
});
return val;
});
As an extra remark: doing it the way you set this up can get you into trouble if one of the words in the array is a substring of one of the other. Watch out for this.
var w = ['ocean','waves','bed', 'swimming'];
$.each(w,function(i,w) {
jQuery('.story').html(function(i,val) {
val = val.replace(w,'<a href="" class="' + w + '">' + w + '<\/a>');
return val;
});
});
JS FIDDLE: http://jsfiddle.net/8XWf3/22/

Add string before a keyword - javascript

I have a forum and I would like to automatically parse some of the major links. For example, if a user makes a post like this:
You should visit StackOverflow. I found it on Wikipedia.
it would automatically parse it like this:
You should visit StackOverflow. I found it on Wikipedia.
Is this even doable using JavaScript only?
Thanks for assistance. :-)
What you want to create a clean and extensible code is create a library of word => link then you can iterate over that and do your replace inside your code.
Here is a fiddle demo doing that http://jsfiddle.net/MjV84/
$(function() {
var text = $('#foo').text(),
library = {
stackoverflow: 'http://stackoverflow.com',
wikipedia: 'http://wikipedia.com'
},
name;
for (name in library) {
text = text.replace(new RegExp(name, 'gi'), function(word) {
return ''+word+'';
});
};
$('#foo ').html(text);
});​
If you're pre-processing the text, you can use the replace function with a callback and a regular expression using an alternation:
var str = "You should visit StackOverflow. I found it on Wikipedia.";
str = str.replace(/StackOverflow|Wikipedia|etc/gi, function(m) {
var href;
switch (m.toLowerCase()) {
case "stackoverflow";
href = "http://stackoverflow.com";
break;
case "wikipedia";
href = "http://en.wikipedia.org";
break;
// ...and so on...
}
return '' + m + '';
});
YMMD points out that the above requires defining each keyword twice, which is true. When I've had to do this with a large number of keywords, I've done it by having an object with the keywords as keys, the href values as values, and built the expression dynamically:
// ==== Setup code you presumably do once
// The substitutions -- make sure the keys are in lower case
var substitutions = {
"stackoverflow": "http://stackoverflow.com",
"wikipedia": "http://en.wikipedia.org",
// ...and so on...
};
// Build the regex. Here I've used `Object.keys` which is an ES5 feature
// but you can use an ES5 shim (since it's something a shim can provide).
// Note that if your keywords include any special regular expression
// characters, you'll have to loop through the keys manually and escape
// those.
var subrex = new RegExp(Object.keys(substitutions).join("|"), "gi");
// ==== Where you're using it
var str = "You should visit StackOverflow. I found it on Wikipedia.";
str = str.replace(subrex, function(m) {
return '' + m + '';
});
Live example | source
Yes, use String.replace(regex, replaceString) to do that.
Here is an example:
var text = "You should visit StackOverflow. I found it on Wikipedia.";
var newText=text.replace(/stackoverflow/gi,
"<a href='http://www.stackoverflow.com/'>StackOverflow</a>");
The g stands for global, so it will replace all instances, and the i means case-insensitive search.
In case you are replacing common words, like "dictionary" to link to dictionary.com it would be better if you only replaced it if your users added a special tag, for example:
"You should visit StackOverflow. I found it on Wikipedia."
shouldn't be replaced with links unless it was written like this:
"You should visit &StackOverflow. I found it on Wikipedia."
Then your method would just need to add the special symbol.
Also, I would have the data in an array like this:
var linkArray = [ ["StackOverflow", "http://www.stackoverflow.com/", "Description"],
["Wikipedia", "http://wikipedia.org/", "Free encyclopedia"] ];
Then create a loop to find and replace the instances:
function addLinks(textInput) {
for (var i=0; i<linkArray.length; i++) {
textInput = addLink(textInput, linkArray[i]);
}
return textInput;
}
function addLink(textInput, link) {
var replaceString = "<a href=\"" + link[1] + "\" title=\""
+ link[2] + "\">"
+ link[0] + "</a>";
return textInput.replace(new RegExp("&"+link[0], "gi"), replaceString);
}
All the previous answers using the i modifier on the regular expression fail if the target
string contains variants of the substitution strings differing by case. This is because the
target string substring does not match the substitutions attribute name.
This version solves this by capturing each of the substitution strings and searching the arguments array for the found string.
function substitute (str) { 'use strict';
var substitutions = {
"Stack Overflow": "http://stackoverflow.com",
"Wikipedia": "http://en.wikipedia.org",
// ...and so on...
},
skeys = Object.keys (substitutions);
// build regexp which will capture each match separtely
return str.replace (new RegExp ('(' + skeys.join(")|(") + ')', "gi"), function (m0) {
// Now scan the arguments array (omitting the last two arugments which
// are the source string and match index)
for (var ai, i = arguments.length - 2; --i;) {
// The index of the argument (less 1) corresponds to the index in skeys of
// the name in the substitutions
if ((ai = arguments[i])) {
return '' + ai + '';
}
}
return m0;
});
}
var str = "You should visit stack overflow. I found it on Wikipedia.";
// check in console log that links are correctly built.
console.log (substitute (str));
document.write (substitute (str));
See the jsfiddle : http://jsfiddle.net/NmGGN/

Extracting 1 or more hyperlinks from paragraph text in Javascript using Regular Expression

Sorry to bother you guys again, but here's my dilemma.
There must be a "better" regular expression to identify HTML link from a paragraph text (there can be more than 1 html links in the text). How do I extract all the link and anchor it in javascript?
My attempt (in javascript) is like this:
var urlPattern = "(https?|ftp)://(www\\.)?(((([a-zA-Z0-9.-]+\\.){1,}[a-zA-Z]{2,4}|localhost))|((\\d{1,3}\\.){3}(\\d{1,3})))(:(\\d+))?(/([a-zA-Z0-9-._~!$&'()*+,;=:#/]|%[0-9A-F]{2})*)?(\\?([a-zA-Z0-9-._~!$&'()*+,;=:/?#]|%[0-9A-F]{2})*)?(#([a-zA-Z0-9._-]|%[0-9A-F]{2})*)?";
function extractURLs(s) {
return s.match(new RegExp(urlPattern));
}
//s is of type String
//For testing...
var text = "Check this video out http://ww w.youtube.com/watch?v=y3U3R3b1dOg or http://www.youtube.com/watch?v=sX6Vm0MoPCY";
alert(extractURLs(text));
(spaces on hyperlink has been deliberately added here to allow posting of question in SO).
Result: I only get the 1st hyperlink and not the second one....
Has anybody done something similar or better that I can utilize?
Thanks in advance.
Use the "g" modifier:
function extractURLs(s) {
return s.match(new RegExp(urlPattern, "g"));
}
var urlPattern = "(https?|ftp)://(www\\.)?(((([a-zA-Z0-9.-]+\\.){1,}[a-zA-Z]{2,4}|localhost))|((\\d{1,3}\\.){3}(\\d{1,3})))(:(\\d+))?(/([a-zA-Z0-9-._~!$&'()*+,;=:#/]|%[0-9A-F]{2})*)?(\\?([a-zA-Z0-9-._~!$&'()*+,;=:/?#]|%[0-9A-F]{2})*)?(#([a-zA-Z0-9._-]|%[0-9A-F]{2})*)?";
function extractURLs(s) {
return s.match(new RegExp(urlPattern));
}
var text = "Check this video out http://www.youtube.com/watch?v=y3U3R3b1dOg or http://www.youtube.com/watch?v=sX6Vm0MoPCY";
var results = extractURLs(text);
alert(extractURLs(results[0] + ", " + results[1]));
It is better to write it as,
var urlPattern = /(https?|ftp)://(www\\.)?(((([a-zA-Z0-9.-]+\\.){1,}[a-zA-Z]{2,4}|localhost))|((\\d{1,3}\\.){3}(\\d{1,3})))(:(\\d+))?(/([a-zA-Z0-9-._~!$&'()*+,;=:#/]|%[0-9A-F]{2})*)?(\\?([a-zA-Z0-9-._~!$&'()*+,;=:/?#]|%[0-9A-F]{2})*)?(#([a-zA-Z0-9._-]|%[0-9A-F]{2})*)?/g;
function extractURLs(s) {
return s.match(urlPattern);
}
Here urlPattern is pre-compiled, rather than compiling the RegEx everytime the function is called, hence results in petter performance.

Categories