ng-bind-html get first letter of html content - javascript

I am having a situation where i am using ng-bind-html for html binding.
I would like to get the first charactor of html content excluding the html tags.
Below is my sample code.
<span class="first-letter">{{firstLetter}}</span>
<div id="myDiv" ng-CLoak data-ng-bind-html="trustAsHtml(data.ContentDescription)" class="{{currentFont}}"></div>
my html string would look like following
<p><span>hii my content</span></p>
the starting and ending tags are un predictable.
i would like to get first letter "h" not "<"
Thanks in advance.

You can let the browser strip html for you using the textContent property
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
and since you are interested only in that first letter, than you probably don't need the ng-bind-html :)
In case you want to highlight that first letter, then use CSS :first-letter
https://developer.mozilla.org/en-US/docs/Web/CSS/%3A%3Afirst-letter

You can remove HTML tags and simply access first letter as we do in an array like this.
var regex = /(<([^>]+)>)/ig
, body = "<p><span>hii my content</span></p>"
, result = body.replace(regex, "");
console.log(result[0]);
Using jQuery
console.log($('<p><span>hii my content</span></p>').text()[0]);
It will give you "h"

if your contet
<p class="first-letter"><span>hii my content</span></p>
then
$(".first-letter").text().substring(0,1)
would return you the first letter no matter how many levels of nesting are there within the class .first-letter

Related

How to render only parts of a string as HTML

I want to render a text as common HTML and parse occurrences of [code] tags that should be output unrendered - with the tags left untouched.
So input like this gets processed accordingly:
<p>render as HTML here</p>
[code]<p>keep tags visible here</p>[/code]
<p>more unescaped text</p>
I've regexed all code-tags but I have no idea how to properly set the text of the element afterwards. If I use jQuery's text() method nothing gets escaped, if I set it with the html() method everything gets rendered and I gained nothing. Can anybody give me a hint here?
Try replacing [code] with <xmp> and [/code] with </xmp> using regex or alike, and then use the jQuery html() function.
Note that <xmp> is technically deprecated in HTML5, but it still seems to work in most browsers. For more information see How to display raw html code in PRE or something like it but without escaping it.
You could replace the [code] and [/code] tags by <pre> and </pre> tags respectively, and then replace the < within the <pre> tags by & lt;
A programmatic solution based on Javascript is as follows
function myfunction(){
//the string 's' probably would be passed as a parameter
var s = "<p>render as HTML here</p>\
[code]<p>keep tags visible here</p>[/code]\
<p>more unescaped text</p>";
//keep everything before [code] as it is
var pre = s.substring(0, s.indexOf('[code]'));
//replace < within code-tags by <
pre += s.substring(s.indexOf('[code]'), s.indexOf('[/code]'))
.replace(new RegExp('<', 'g'),'<');
//concatenate the remaining text
pre += s.substring(s.indexOf('[/code]'), s.length);
pre = pre.replace('[code]', '<pre>');
pre = pre.replace('[/code]', '</pre>');
//pre can be set as some element's innerHTML
return pre;
}
I would NOT recommend the accepted answer by Andreas at all, because the <xmp> tag has been deprecated and browser support is totally unreliable.
It's much better to replace the [code] and [/code] tags by <pre> and </pre> tags respectively, as raghav710 suggested.
He's also right about replacing the < character with <, but that's actually not the only character you should replace. In fact, you should replace character that's a special character in HTML with corresponding HTML entities.
Here's how you replace a character with its corresponding HTML entity :
var chr = ['&#', chr.charCodeAt(), ';'].join('');
You can replace the [code]...[/code] with a placeholder element. And then $.parseHTML() the string with the placeholders. Then you can insert the code into the placeholder using .text(). The entire thing can then be inserted to the document (run below or in JSFiddle).
var str = "<div><b>parsed</b>[code]<b>not parsed</b>[/code]</div>";
var placeholder = "<div id='code-placeholder-1' style='background-color: gray'></div>";
var codepat = /\[code\](.*)\[\/code\]/;
var code = codepat.exec(str)[1];
var s = str.replace(codepat, placeholder);
s = $.parseHTML(s);
$(s).find("#code-placeholder-1").text(code);
$("#blah").html(s);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text
<div id="blah">place holder</div>
Around
The code above will need some modifications if you have multiple [code] blocks, you will need to generate a unique placeholder id for each code block.
If you may be inserting untrusted structure code, would highly recommend using large random number for the placeholder id to prevent a malicious user from hijacking the placeholder id.

Add actual HTML elements to PRE/CODE contents

I'm trying to create a quick/dirty way to add some syntax highlighting for pre/code tags in html using javascript.
The problem i'm running into, is that if i edit either the text() or html(), I get escaped content. That is, the added tags render as pre/code, or i get a bunch of eascape characters.
Consider the following html:
<pre>
<code class="target">
public interface __iIFoo { }
public class __tBar : __iIFoo { }
var list = new List__/__iIFoo\__();
</code>
</pre>
The goal here is to replace occurrences of __iIFoo with:
<span class="interface">IFoo</span>
So that it can be highlighted with css. And of course, when it's rendered, I don't want to see the actual SPAN tag.
Here's what I've tried:
$(function(){
var iPatt = /__i\w+/g
$.each($(".target").text().match(iPatt), function(i,match){
var replace = '<span class="interface">'+match.substring(3)+'</span>';
$(".target").text(function(){
return $(this).text().replace(match, replace);
});
});
});
This works, BUT, the span tags I'm adding show up in the rendered content e.g. they are just like all the other pre code. I don't want to see it!
Use .html() instead of .text(). When you use .text(), the value is the literal text that you want users to see, so it replaces special HTML characters with entities so they'll show up literally.
DEMO
.text() treats value as text and .html() render it as html content
$(".target").html(function () { //replace text with html
return $(this).text().replace(match, replace);
});
Try using it with html instead:
$(function(){
var iPatt = /__i\w+/g
$.each($(".target").text().match(iPatt), function(i,match){
var replace = '<span class="interface">'+match.substring(3)+'</span>';
$(".target").html(function(){
return $(this).text().replace(match, replace);
});
});
});
As I said in my comment, change the html rather than the text (fiddle).
As a side-note, it's worrisome that you're completely overwriting the contents of .target every time you encounter a match. You should take advantage of RegExp capture groups and perform only one assignment.
(function () {
var iPattern = /__i(\w+)/g,
iTemplate = "<span class='interface'>$1</span>";
$(".target").each(function () {
this.innerHTML = this.innerHTML.replace(iPattern, iTemplate);
});
})();

Script or CSS to bold all words that are all CAPS

I'm a bit of a n00b but am trying to figure out a quick way to go through my html and put a <strong> tag on words that are in all caps. Can this be done through CSS or will it have to be JavaScript? Either way, what would be the method? Thanks!
Get the Content of your element (in my example a plain div), and search with a regex for capsed words.
var div = document.querySelector("div");
var html = div.innerHTML;
html = html.replace(/(\b[A-Z]{2,}\b)/g,"<strong>$1</strong>");
div.innerHTML = html;
The keypoint is the characterclass [A-Z] which only accepts capital letters enclosed in word borders \b.
Docs for replace.
Example

removing html tags from string

I am trying to remove the HTML tags from a string. Right now I am able to remove the complete HTML tags like for example <div class="test">dadsasdsad</div> gives me the output dadsasdsad.
But I'm unable to remove partial tags like class="test">dadsasdsad</div> or testing<div class=
The regular expression that Ive used is
strippedText[i] = fragments[i]
.replace(/<(?:.|\n)*?>/gm, '')
.replace(replaceAT, '<span style=font-weight:800>')
.replace(replaceET, '</span>');
Here fragments[i] contains the input <div class="test">dadsasdsad</div>;
strippedText[i] = fragments[i]
// full tags
.replace(/<[^>]+>/gm, '')
// partial tags
.replace(/^[^>]+>/gm, '')
.replace(/<[^>]+$/gm, '');
Note that ^ has different meanings: "not" within brackets, "start" outside brackets.
/gm should not be necessary for partial tags, but I left them as I don't know your context and how you're getting partial tags.
my simple JavaScript library has a function called "strip_tags()" which does the long work for you.
Just say that you have a sentence loaded with HTML formatting tags, and you want to remove them, simply do it like this:
strip_tags("<p>This <em>sentence</em> contains <strong>a lot</strong> of tags!</p>");
This will output "This sentence contains a lot of tags!" (tested on the documentation website).
To read more about this function, please read the documentation at http://docs.funcjs.webege.com/strip_tags().html and if possible, leave feedback through the Feedback Form on the website.
Hope this helps you and anyone else with the same problem! :)
Using javascript you can do this:
function removeHTMLTags(htmlString) {
if(!htmlString) { return; }
var mydiv = document.createElement("div");
mydiv.innerHTML = htmlString;
return mydiv.textContent || mydiv.innerText || '';
}
[Source]

escape less / greater than javascript

I'm having a problem trying to escape some code... Basically, I want to escape "<" and ">" but I want them to APPEAR in my #output div as "<" and ">". Currently, they appear as as "<" and ">" on the page.
This is obviously to prevent anyone exploiting / injecting scripts on the page. This is my code:
var textval = $("#textarea").val(); //textarea
filtered = textval.replace(/</gi,"<"); //replace "<"
$("#output").html(filtered); //insert textarea data into div
Can anybody spot what I am doing wrong, or are there any better ways of doing this?
Many thanks
EDIT: I do want SOME html tags (like <b> to work, so I can't use $.text(); unfortunately..)
Try this:
var textval = $("#textarea").val();
$("#output").text(textval);
jQuery offers two methods - $.text() and $.html() where the method names speak for themselves :)
A little different replace, but works for me (even with .html()).
Demo
var str = $('#textarea').val();
$('#result').html(str.replace(/<|>/ig,function(m){
return '&'+(m=='>'?'g':'l')+'t;';
}));
<textarea id="textarea">
Hello, <b>World</b>!
</textarea>
<div id="result"></div>
(This is just to verify it can be done, .text() is the better approach)

Categories

Resources