Javascript replace() using html entities not working - javascript

I've got the following script, which successfully replaces < and > with the code indicated below. The idea here is that a user would put into the text box if they want "Bold me" to appear bolded on their blog.
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('<', '<span class="bold">'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('>', '</span>'));
});
The problem comes with other html entities. I'm going to simply my example. I want to replace the [ html entity with a paragraph tag, but none of the lines in this script work. I've tried documenting each code that related to the '[' character.
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('[', '<p>'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('&lbrack;', '<p>'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('&lsqb;', '<p>'));
});
$('.blogbody').each(function() {
var string = $(this).html();
$(this).html(string.replace('&lbrack;', '<p>'));
});
Any thoughts on this would be greatly appreciated! Thanks!

The character '[' is not a character entity so it is not encoded. Just pass it directly to replace:
string.replace('[' , '<p>')

Related

Search that highlights text is having problems with special characters

I took this code from a blog which I don't remember the URL. The code is supposed to find in a list with many sections the text written by the user in an input field. If there is a match, the text will be highlighted; and if there is no match, the whole section will hide.
I've made a plunker so you can see how it works: Here's the link
This is the JS code:
$(document).ready(function() {
var $container = $('#global_div');
if (!$container.length) return true;
var $input = $('#searcher'),
$notfound = $('.not-found'),
$items = $container.find('.row'),
$item = $(),
itemsIndexed = [];
$items.each(function() {
itemsIndexed.push($(this).text().replace(/\s{2,}/g, ' ').toLowerCase());
});
$input.on('keyup', function(e) {
$items.each(function() {
$item = $(this);
$item.html($item.html().replace(/<span class="highlight">([^<]+)<\/span>/gi, '$1'));
});
var searchVal = $.trim($input.val()).toLowerCase();
if (searchVal.length) {
for (var i in itemsIndexed) {
$item = $items.eq(i);
if (itemsIndexed[i].indexOf(searchVal) != -1)
$item.removeClass('is-hidden').html($item.html().replace(new RegExp(searchVal + '(?!([^<]+)?>)', 'gi'), '<span class="highlight">$&</span>'));
else
$item.addClass('is-hidden');
}
} else $items.removeClass('is-hidden');
$notfound.toggleClass('is-visible', $items.not('.is-hidden').length == 0);
});
});
So far so good, but the problem is when there are certain characters in the html text or when writing some special characters in the input field. Please open the plunker so you can do the tests I'm about to tell you:
When writing down the letters "a", "s" or "n", you can see how it shows the &amp ; and &nbsp ; of the html. Also when writing down "&", and the whole thing breaks when writing a "." (point).
As I couldn't fix this, I added this code to avoid people from writing special characters in the input (this code isn't in the plunker, so you can test the errors):
$("#searcher").keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
return isValid(character);
});
function isValid(str) {
return !/[~`!##$%\^&*()+=\-\[\]\\';/{}|\\":.<>\?]/g.test(str);
}
But there is still the problem when there are characters like &amp ; and &nbsp ; in the html and users write in the input field the letter "a", "s" or "n" ..or depending which other weird character be on the html.

Identifying if code between code tags is JavaScript or HTML

I am trying to match block of code to check if is html or javascript code, i tried doing this but am having problem while when have this html element "<div></div>" or php <? echo '';> inside javascript code it will match it as html element.
Please can someone help me with best way to archive this?
<script>
$(document).ready(function(){
function AssignLang(theLanguage){
var regex = /(<([^>]+)>|<([^>]+)>)/ig;
//var regex = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>";
if(theLanguage.match(regex)){
var lang = 'markup';
}else{
var lang = 'javascript';
}
return lang;
}
$('pre code').each(function () {
var the = $(this).html();
/*I tried here to match from 0 to 50 but is not going to help because if the javascript tag begin with <script> still show as html
var theLanguage = the.replace(/\s/g, '').substring(0,50);
*/
var theLanguage = the.replace(/\s/g, '');
var langType = AssignLang(theLanguage);
$(this).addClass("fullcoded language-"+langType);
alert(theLanguage+"-"+langType);
});
});
</script>
Here am matching code inside pre and code element
<pre><code>
function check() {
var delvar = "<? $_POST["del"]; ?>";
var answer = confirm("Are you sure you want to delete the article?")
if (answer) {
window.location = "adm-site.php?del=" + delvar + "&delete=true";
}
}
</code></pre>
<pre><code>
<select name="del">
<option value="none" SELECTED></option>all articles echo'ed here by php
</select>
</code></pre>
Here is a link to https://jsfiddle.net/ppu9qw3n/
This is the regex I'm using /\w+\s\w+\(\)/i
\w+ matches 1 or more a-z, A-Z, 0-9 and _
\s matches 1 space
\( and \) matches ()
Basically I'm searching for a pattern consisting of function functionName() in the code between code tags. If a match is found then it's JavasScript code or else it's HTML code.
This is how you can implement the JavaScript:
$(document).ready(function(){
var regex = /\w+\s\w+\(\)/i;
$('pre code').each(function () {
var v = $(this).html();
if(regex.test(v)){
alert(v+'-'+'THIS IS JAVASCRIPT CODE')
}
else{
alert(v+'-'+'THIS IS HTML CODE')
}
});
});
Check it here on jsfiddle. It's working.
https://jsfiddle.net/swzaf5r1/

Find alphanumeric characters, text and replace with HTML

I'm trying to find and replace text in an HTML. And adding a bold element around the text.
For example, lets say I have the following text:
<div>This is a test content and I'm trying to write testimonial of an user.</div>
If user searches for "test" in my HTML string, I need to show all text containing search text in bold.
<div>This is a <b>test</b> content and I'm trying to write <b>test</b>imonial of an user.</div>
This is working using the below code:
$.fn.wrapInTag = function(opts) {
var o = $.extend({
words: [],
tag: '<strong>'
}, opts);
return this.each(function() {
var html = $(this).html();
for (var i = 0, len = o.words.length; i < len; i++) {
var re = new RegExp(o.words[i], "gi");
html = html.replace(re, o.tag + '$&' + o.tag.replace('<', '</'));
}
$(this).html(html);
});
$('div').wrapInTag({
tag: 'b',
words: ['test']
});
But the above javascript approach fails if I search something like:
*test or /test
Regex doesn't support here.
There are multiple approaches over net but none of them worked for alphanumeric text.
This is how I would perform the text highlight:
$("#search").keyup(function(){
$("#text").html($("#text").html().replace("<b>", "").replace("</b>", ""));
var reg = new RegExp($(this).val().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"),"g");
$("#text").html($("#text").text().replace(reg, "<b>"+$("#search").val()+"</b>"));
});
Here is the JSFiddle demo
You need to escape the RegExp input. See How to escape regular expression in javascript?
function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

Escape characters in String in a HTML page?

I have a string in the below non-escaped format in a HTML page:
<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>
What I need is to use jQuery/JavaScript to replace that string with just the link "SomeThing".
I have looked at some examples in StackOverflow, but they don't seem to work. I'm just getting started with jQuery and JavaScript, so would appreciate any help here.
Any ideas?
Try html() and text() in jquery to decode:
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var decoded = $('<div />').html(str).text();
alert($(decoded).text());
See Fiddle demo
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var helper = document.createElement('p');
// evaluate as HTML once, text now "<a href..."
helper.innerHtml = str;
// evaluate as HTML again, helper now has child element a
helper.innerHtml = helper.innerText;
// get text content only ("SomeThing")
alert(helper.innerText);
Here is a possible starting point.
Hope this gets you started!
function parseString(){
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var begin = str.indexOf('\">',0)+2; //--determine where the opening anchor tag ends
var end = str.indexOf('</a>',0); //--determine where the closing anchor tag begins
var parsedString = str.substring(begin,end); //--grab whats in between;
/*//--or all inline
var parsedString = str.substring(str.indexOf('\">',0)+2,str.indexOf('</a>',0));
*/
console.log(parsedString);
}
parseStr();

Select a Tag with a Selector from a Text Variable using jQuery

I have a string which contains text and some <a> tags in it; I want to know how I can select a tag from the variable and loop it. I tried the following but it didn't work:
var text = `some string here with http:something.com more string and more links also`;
$('a', text).each(function() {
var string = $(this).html();
$(this).html(string.substring(0, length-1)+(string.length > length ? end : ''));
});
You need to wrap the text in a div (or other element) then find() it:
var text = 'some string here with http:something.com more string and more links also';
text = $('<div>' + text + '</div>');
text.find('a').each(function() {
var length = 10;
var end = '...';
var string = $(this).html();
$(this).html(string.substring(0, length) + (string.length > length ? end : ''));
});
var text = text.html();
// Put it into a textarea
$('#myTextarea').val(text);
Replace
$('a', text).each(function() {
with
$(text, 'a').each(function() {
and see if it works.

Categories