Replace selected text inside p tag - javascript

I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code.
<p id="1-pagedata">
(d) 3 sdsdsd random: Subject to the classes of this random retxxt wee than dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo
</p>
This is the javascript code.
function SelectText() {
var val = window.getSelection().toString();
alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}
$(function() {
$('#hello').click(function() {
SelectText();
});
});
I have also created a jsfiddle of the code.
https://jsfiddle.net/zeeshidar/w50rwasm/
Any ideas?

You can simply do $("#1-pagedata").html('New text here');

Since your p doesn't content HTML but just plain text, your can use both html() or text() as getter and setter.
Also, thanks to jQuery Chaining you can do all your replacements in one statement. So, assuming your RegExp's and replacement values are correct, try:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));

Related

Sanitizing input to stick into a hidden input value with jQuery

Maybe I am confusing this a bit, but I have a piece of code that works like the following:
$("#myButton").on('click', function(){
var myValue = $('#myInput').val();
listSize++;
var listItem = "<li>" + myValue + "<input type='hidden' name='foo" +
listSize + "' value='" + myValue + "' /></li>";
$("ol.myList").append(listItem);
});
If the text input value contains for example, a ', then this code breaks in terms of correctly adding the hidden input value.
I was thinking that using encodeURIComponent would do the trick, but it does not.
What's the proper way to handle this?
Instead of doing this with html strings, create an actual element and set it's value property using val().
You can sanitize any possible html out of it by first inserting the string into a content element as text and retrieving it as text.
Note that the value property does not get rendered in the html the same as value attribute does so quotes are not an issue
$("#myButton").on('click', function(){
// sanitize any html in the existing input
var myValue = $('<div>', {text:$('#myInput').val())).text();
listSize++;
// create new elements
var $listItem = $("<li>",{text: myValue});
// set value of input after creating the element
var $input = $('<input>',{ type:'hidden', name:'foo'+listSize}).val(myValue);
//append input to list item
$listItem.append($input);
// append in dom
$("ol.myList").append($listItem);
});
I think this is what you are looking for:
$("#myButton").on('click', function(){
var myValue = $('#myInput').val();
listSize++;
var listItemHTML = "<li>" + myValue + "<input type='hidden' name='foo'></li>";
$(listItemHTML).appendTo('ol.myList').find('input[type=hidden]').val(myValue);
});
The appendTo function returns a reference to the just appended element.
Calling the val() function on the element will render the inserting of a quote useless since it will be interpreted as an actual value.
Safest way would be to write a wrapper
function addslashes (str) {
return (str + '')
.replace(/[\\"']/g, '\\$&')
.replace(/\u0000/g, '\\0')
}
var test= "Mr. Jone's car";
console.log(addslashes(test));
//"Mr. Jone\'s car"

jQuery replacing letters with HTML

I am pulling some text from a database and I have , and I would like to replace them with <br> don't really know why it's not working any ideas?
JS Code
$( document ).ready(function() {
//.MoreInfoText
var $infotext = $('.MoreInfoText').text().replace(/\+/g, '<br>');
$.each($infotext, function() {
$('.MoreInfoText').text($infotext);
});
});
Text as its coming from the DB:
Ryan open 30/01/1998, ryan added numberOFIteams of NameOFIteams
1st use replace(/\,/g, '<br>')); yours only replace +
(note the g means replace all, you can also make the search case-insensitive pass the "i" parameter ex: /gi)
2nd use $('.MoreInfoText').html() so your <br> are treated as HTML instead of string.
$( document ).ready(function() {
//.MoreInfoText
$('.MoreInfoText').html($('.MoreInfoText').text().replace(/\,/g, '<br>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="MoreInfoText">11111,22222,33333,44444,55555</span>
It should be .replace(/,/g,"<br>") so all ,s get replaced with <br>. Right now it's replacing + with <br>.
Also to iterate over every element with class MoreInfoText replacing , with <br> modify your code like this:
$('.MoreInfoText').each(function() {
var text = $(this).text().replace(/,/g, '<br>')
$(this).html(text);
});
Try to use the following code:
$( document ).ready(function() {
//.MoreInfoText
var $infotext = $('.MoreInfoText').text().replace(',', ' ');
$.each($infotext, function() {
$('.MoreInfoText').text($infotext);
});
});
I would recommend avoiding the usage of <br /> for adding line breaks, you may consider using <p> instead.
$( document ).ready(function() {
//.MoreInfoText
$('.MoreInfoText').each(function() {
var moreArray = $(this).text().split(',');
var $infotext = '';
for(var i = 0; i < moreArray.length; i++){
$infotext += '<p>' + moreArray[i] + '</p>';
}
$(this).empty().html($infotext);
});
});
If paragraphs are not already placed each on a new line, you can add a CSS rule for that. This helps separating the content from the presentation, which is what CSS is for.

Generated HTML by javascript is not formatted correctly

I want to make a input field where I can search for friends in a list, these friends I retrieve from a xml file and I generate them using javascript
The code I generate this with:
friendListInDiv = document.createElement("p");
var link = document.createElement("a");
link.onclick = function() {
openChat(friendsXML[i].textContent)
};
var friendText = document
.createTextNode(friendsXML[i].textContent + ":"
+ statusXML[i].textContent);
link.appendChild(friendText);
friendListInDiv.appendChild(link);
friendDiv.appendChild(friendListInDiv);
Now the problem I'm facing I have demonstrated in a jsfiddle:
https://jsfiddle.net/x897pv9o/
As you can see if you type in "j" in the top input bar it hides all friends but type "j" in the bottom one it will still display "Joske"
This is because these tags
<div id="friendlist"><p><a>
Joske:
Offline</a></p><p><a>
Tom:
Offline</a></p><p><a>
Dirk:
Offline</a></p></div>
are not being formatted correctly, how can I make them format correctly?
As Shaunak D mentioned in a comment, you can use .trim() to remove preceding and trailing whitespace, including new lines, from text. You can either use this on your text content when creating the node, or use it in your search function to exclude new lines.
In document.createTextNode:
var friendText = document.createTextNode(
friendsXML[i].textContent.trim() + ":" + statusXML[i].textContent);
In $('#searchinfriend').keyup:
$('#searchinfriend').keyup(function () {
var valThis = $(this).val().toLowerCase();
$('#friendlist p a').each(function () {
var text = $(this).text().trim().toLowerCase();
(text.indexOf(valThis) == 0) ? $(this).show() : $(this).hide();
});
});

li append function not work

I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>

case insensitive word boundaries with regExp

for some reason the gi modifier is behaving as case sensitive. Not sure what's going on, but maybe someone knows why this is. it works fine when the cases are the same. This JSFiddle will demonstrate my problem. Code below. Thanks.
javaScript:
var search_value = $('#search').val();
var search_regexp = new RegExp(search_value, "gi");
$('.searchable').each(function(){
var newText =(this).html().replace(search_value, "<span class = 'highlight'>" + search_value + "</span>");
$(this).html(newText);
});
HTML:
<input id = "search" value = "Red">
<div class = "searchable">this should be red</div>
<div class = "searchable">this should be Red</div>
Correct Code is
var search_value = $('#search').val();
var search_regexp = new RegExp(search_value, "gi");
$('.searchable').each(function(){
// var newText =$(this).html().replace(search_value, "<span class = 'highlight'>" + search_value + "</span>");
var newText =$(this).html().replace(search_regexp, function(matchRes) {
return "<span class = 'highlight'>" + matchRes + "</span>";
});
$(this).html(newText);
});
output
Fiddle
Issues with your code:-
First: search_regexp - You haven't used search_regexp anywhere in your code
Your Code
var newText =$(this).html().replace(search_value, "<span class = 'highlight'>" + search_value + "</span>");
Second
You are using search_value to replace. It will make both Red and red to either Red or red after replace.
eg: if search_value is Red then your output will be
this should be Red
this should be Red
you should use matched result instead of search_value
Third: How to use RegExp with replace function?
Correct Method is
var newText =$(this).html().replace(search_regexp, function(matchRes) {
return "<span class = 'highlight'>" + matchRes + "</span>";
});
Explanation
replace(<RegEx>, handler)
Your code isn't using your regex in the replace call, it's just using the search_value. This JSBin shows your code working: http://jsbin.com/toquz/1/
Do you actually want to replace the matches with the value (changing lowercase instances to uppercase in this example)? Using $.html() will also get you any markup within that element, so keep that in mind as well (in case there's a chance of having markup in the .searchable elements along with text.
Might be easier to do:
function highlight(term) {
var search_regexp = new RegExp(term, "gi");
$('.searchable').each(function(){
if (search_regexp.test($(this).html())) {
var highlighted = $(this).html().replace(search_regexp, function(m) {
return '<span class="highlight">'+m+'</span>';
});
$(this).html(highlighted);
}
});
}
Your original code in the JSBin is the highlightReplace() function.

Categories

Resources