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.
Related
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"
I have a string that conains HTML. In this HTML I have a textbox with text inside:
<div class="aLotOfHTMLStuff"></div>
<textbox>This textbox must be terminated! Forever!</textbox>
<div class="andEvenMoreHTMLStuff"></div>
Now I want to remove the textbox from that string, including the text inside. The desired result:
<div class="aLotOfHTMLStuff"></div>
<div class="andEvenMoreHTMLStuff"></div>
How can I achieve it? The two main problems: It is a string and not part of the DOM and the content inside the textbox is dynamic.
Here is an example that will look for the opening and closing tags in the string and replace anything in between.
const template = document.querySelector('#html')
const str = template.innerHTML
function removeTagFromString(name, str) {
const reg = new RegExp('<' + name + '.*>.*<\/'+ name +'.*>\\n*', 'gm')
return str.replace(reg, '')
}
console.log('before', str)
console.log('after', removeTagFromString('textbox', str))
<template id="html">
<div class="aLotOfHTMLStuff"></div>
<textbox>This textbox must be terminated! Forever!</textbox>
<div class="andEvenMoreHTMLStuff"></div>
</template>
If it is text string not HTML, you can convert it to DOM:
var str = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
var $dom = $('<div>' + str + '</div>');
Then remove element from DOM:
$dom.find('textbox').remove();
If you need, can get string back:
console.log($dom.html());
Try this:
var string = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
if ( string.includes("<textbox>") ) {
var start = string.indexOf("<textbox>");
var stop = string.indexOf("</textbox>");
string = string.replace(string.slice(start, stop+10), "");
}
console.log(string);
You can use parseHTML to convert string to html,
like..
var str = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
var a = $.parseHTML(str);
var newstr = "";
a.forEach(function(obj) {
if ($(obj).prop('tagName').toLowerCase() != "textbox") {
newstr += $(obj).prop("outerHTML")
}
});
It's very simple and you can remove any tag in future by just replacing "textbox"
It is a string and not part of the DOM and the content inside the
textbox is dynamic.
So that html is in a js variable of type string? like this?:
var string = '<div class="aLotOfHTMLStuff"></div><textbox>This textbox must be terminated! Forever!</textbox><div class="andEvenMoreHTMLStuff"></div>';
So in that case you could use .replace(); like this:
string = string.replace('<textbox>This textbox must be terminated! Forever!</textbox>', '');
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"));
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();
});
});
feel like im coming here way too often to ask questions but yet again I am stuck. I am attempting to select a textarea and allow myself to edit the text in another textarea, which works fine using textboxs but not with textareas. Every time I click on the div container I am getting an undefined result when looking for the textarea. Below is the code.
jQuery
$(".textAreaContainer").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID ).find(':input');
alert(t.attr('id'));
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
//var textboxId = $('div.textAreaContainer').find('input[type="textArea"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" Textarea shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
t.attr('id') should be returning textbox1(or similar) but instead just returns undefined.
I have tried .find(':textarea'),.find('textarea'),.find(text,textArea),.find(':input') and quite a few others that I have found through google but all of them return undefined and I have no idea why. A demo can be found here, http://jsfiddle.net/xYwaw/. Thanks in advance for any help guys, it is appreciated.
EDIT: Below is the code for a very similar example I am using. This does what I want to do but with textboxs instead of textareas.
$('#textAdd').live('click',function() {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Textbox " + textBoxCounter + " <br><div id='container" + counter + "' class='container'><li><input type='text' id='textBox" + textBoxCounter +"' name='textBox" + textBoxCounter + "'></li></div></br>";
document.getElementById("identifier").appendChild(newdiv);
textBoxCounter++
counter++;
});
$(".container").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID).find('input');
alert(divID);
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
alert(t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
// var textboxId = $('div.container').find('input[type="text"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" textbox shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
First up remove the second parameter, 'div', from the first line:
$(".textAreaContainer").live('click','div', function(){
...to make it:
$(".textAreaContainer").live('click', function(){
Then change:
var t = $('#' + divID ).find(':input');
...to:
var t = $(this).find(':input');
Because you already know that this is the container so there's no need to select it again by id. Also the id attributes that you're assigning to your textarea containers have a space in them, which is invalid and results in your original code trying to select the element with '#textAreaContainer 0' which actually looks for a 0 tag that is a descendant of #textAreaContainer. So fixing the code that creates the elements to remove that space in the id is both a good idea in general and an alternative way of fixing this problem.