passing HTML to template in Meteor - regex

I'm making my first Meteor app - a regular expression matcher is the first component that I'm making. It will highlight matching items in an editable string by surrounding the matches with a span tag.
I figured out how to create the tags around matches in vanilla JavaScript:
http://jsbin.com/iXUVUJA/1/
But the way I added it into a Meteor template, the tags are being shown in the browser. Is there a way to have the tags read as html in the browser?
Here is the relevant code from my .js file:
var str = "There are thousands and thousands of uses for corn... All of which I will tell you about right now.";
var regEx = /[A-Z]/g;
if (Meteor.isClient) {
Template.sampleText.someText = function() {
return str.replace(regEx, ("span class='highlighted'>" + "$&" + "</span>") );
};
}
And here is the relevant code from my .html file:
<template name="sampleText">
{{someText}}
</template>
This is the output on the page from the server:
span class='highlighted'>There are thousands and thousands of uses for corn... span class='highlighted'>All of which span class='highlighted'>I will tell you about right now.

You can use Handlebars.SafeString, as seen in the Handlebars documentation. In your case you can do:
if (Meteor.isClient) {
Template.sampleText.someText = function() {
var element = str.replace(regEx, ("span class='highlighted'>" + "$&" + "</span>") );
return new Handlebars.SafeString(element);
};
}

Related

SharePoint List CSR handler are not fired - SharePoint online

I am trying to change style of sharepoint list using CSR. I want to apply bold to title column. I have added these code in JS file and reffered as JSLink(JavaScriptDisplayTemplate) to webpart. On document ready both renderTitleHandler & preRenderHandler are registered and also preRenderHandler are called successfully. But renderTitleHandler are not fired.
Please find my code snippet,
function renderTitleHandler(ctx) {
var fieldVal = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
var title = fieldVal.toString();
var html = '';
html += '<b>' + title + '</b>';
return html;
}
function preRenderHandler(ctx) {
ctx.ListTitle = '<b>' + ctx.ListTitle + '</b>';
}
(function() {
var overrideCtx = {};
overrideCtx.Templates = {};
overrideCtx.Templates.OnPreRender = preRenderHandler;
overrideCtx.Templates.Fields = {
"Title" : {"View" : renderTitleHandler}
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();
Thanks in advance.
Kannan.
Possibilities:
disable Minimal Download Strategy (mds). Sometimes this blocks your
javascripts caused by the async loading in the back of certain OOTB
scripts
remove the debugger;-line (is it possible that your code works when developer tools in your browser are open?)
Edit:
Found an example on my dev environment and i have the word View between quotes:
linkFilenameFiledContext.Templates.Fields = {
"Title": { "View": renderTitleHandler}
};
Hope it helps

Meteor subscriptions using deps

I'm trying to implement a searching feature in a Meteor application that re-subscribes/publishes a collection on every search, so there is only the exact Collection necessary in the client. I'm creating a reactive variable searchString, then changing it to the text in the search box on every search, then splitting the string into tags:
// Client
var searchString = "";
var searchStringDep = new Deps.Dependency;
var getSearchString = function(){
searchStringDep.depend();
return searchString;
}
var handle = Deps.autorun(function(){
var tags = getSearchString().split(" ");
tags = _.map(tags, function(tag){
return tag.replace(/[^\w]/g, "");
}).filter(function(t){
return t.toLowerCase();
});
Meteor.subscribe('results', tags);
});
Template.library.events({
'submit form': function(ev){
ev.preventDefault();
searchString = ev.target.search.value;
searchStringDep.changed();
}
})
Then, publishing a new Collection on the server, based on the tags:
// Server
Meteor.publish('results', function(tags){
regTags = _.map(tags, function(tag) { return new RegExp(tag)});
return Samples.find({tags: {$in: regTags}})
});
So I'm trying to match on regexes, but am having a weird issue where the subscription only changes when I add another tag, but changing existing tags fails.
So if the first searchString was tag1 and the second tag1 tag2, it works fine.
But if the first is tag1 and the second is tag2, the Collection doesn't update.
Any help is appreciated...I'm a beginner to Meteor, so if there is a better way to do what I'm trying to do, all suggestions are welcome. Thanks so much
'change #search': function(){
Meteor.subscribe('sampleResults', $('#search').val()); // or if you want on submit it's the same idea
}
and publish like
Meteor.publish('sampleResults, function(text){
return Samples.find({tags: {$regex: text}});
}
A few things:
1) Meteor has a very nice way of setting up reactive variables with the ReactiveVar component. I would suggest using that rather than creating another dependency for a variable.
2) The name that you are subscribing to: results is different than what is published on the server sampleResults and that can cause issues.
3) If you are on Meteor >= 0.9.1 you should be using Tracker and not Deps. You can use Deps if you want, but the new updated API is Tracker and is probably more stable. See the changelog for more details on that.
4) You don't have to set your Deps.autorun function equal to a variable. So you can have it as:
Tracker.autorun(function() {
// Code here
});

Can a sizzle selector evaluate a regular expression?

I need to select links with a specific format of URLs. Can I use sizzle to evaluate a link's href attribute against a regular expression?
For example, can I do something like this:
var arrayOfLinks = Sizzle('a[HREF=[0-9]+$]');
to create an array of all links on the page whose URL ends in a number?
Give this a try. I've attempted to convert the jQuery regex selector that Kobi linked to into a Sizzle selector extension. Seems to work, but I haven't put it through a lot of testing.
Sizzle.selectors.filters.regex = function(elem, i, match){
var matchParams = match[3].split(',', 2);
var attr = matchParams[0];
var pattern = matchParams[1];
var regex = new RegExp(pattern.replace(/^\s+|\s+$/g,''), 'ig');
return regex.test(elem.getAttribute(attr));
};
In this case, your example would be written as:
var arrayOfLinks = Sizzle('a:regex(href,[0-9]+$)');

How do I linkify text using ActionScript 3

I have a text that I want to linkify (identify URLs and convert them to HTML links). The text could be multi-line, and could contain multiple urls like the example below.
My current actionscript code looks like this
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
private function init():void {
var str:String = "#stack the website for google is http://www.google.com and gmail is http://gmail.com";
//Alert.show(linkify(str),"Error");
txtStatus.htmlText = linkify(str);
}
private function linkify(texty:String):String {
//return texty.replace("/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g",function(m):String { return m.linkify(m);});
//return texty.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m):String {return m.linkify(m);}).replace(/(^|[^\w])(#[\d\w\-]+)/g, function(m2):String{return '#' + m2.substr(1) + ''; });
var pattern:RegExp = /[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g;
var match:String = pattern.exec(texty);
return texty.replace(pattern,'<a href="' + match + '">' +
match + '</a>');
}
]]>
</mx:Script>
The problem with the above script is that it recognizes the first match and uses that across. Also how do i do it for #?
Any help is highly appreciated.
ooph ... why does everybody use regex these days, to accomplish super simple tasks? also, you forgot, that "+" is a valid character for URLs, as a replacement for space, and even an awful lot of other characters may be used, so your pattern would not even match accordingly ...
well, anyway, have a look at AS3 regex metacharacters ...
that'll GREATLY improve your expression's readability and is much more robust...
i'd go with something like this, really:
var r:RegExp = /(?:http|https):\/\/\S*/g;
trace(str.replace(r, function (s:String,...rest):String {
return '' + s + ''
} ));
but the actual point, was the global flag ...
good luck then ... :)
greetz
back2dos

javascript regex multiple occurrence

i have javascript variable having value
var ull="<ul><li>sunil here from mandya </li><li>kumar here</li></ul>"
i want output of alert message of each list content like below
1st alert message =sunil here from mandya
2nd alert message =kumar here
how to accomplish this with regex,please help,, i am new to this
It's not recommended to use a regex on HTML. An XML parser would be better. And even better than that would be using javascript. This will output what you're looking for
var li = document.getElementsByTagName('li');
var liLength = li.length;
for(i=0;i<liLength;i++){
if(document.all){ //IE
alert(li[i].innerText);
}else{ //Firefox
alert(li[i].textContent);
}
}
An alternative, which would be better supported than writing these things yourself would be to use a javascript framework, such as jQuery (like richardtallent suggests).
You'd be able to do something with that in a much less verbose manner, like:
$('li').each(function(){
alert($(this).text());
});
Don't use regex to parse html, use a parser instead
var p = new DOMParser();
var ul = p.parseFromString("<ul><li>sunil here from mandya </li>" +
"<li>kumar here</li></ul>", "text/xml");
var lis = ul.getElementsByTagName("li");
var len = lis.length;
for(var i = 0; i < len; i++)
alert(lis[i].firstChild.nodeValue);
A better bet would be to use JQuery (or just DOM calls) rather than trying to parse HTML using regex.
Also, you should consider not sending users a series of alert() modal dialogs, that would be very annoying to many users.
var str = '<ul><li>sunil here from mandya </li><li>kumar here</li></ul>';
var haystack = str;
var match = haystack.match(/<li>(.+?)<\/li>/);
while (match) {
alert(match[1]);
haystack = haystack.slice(match[0].length);
match = haystack.match(/<li>(.+?)<\/li>/);
}
Of course, if the HTML is actually on the page, it would be much, much better to iterate through the DOM.