I have a div which is content editable, and JS function to search the input for certain words. If a match is found, the content od the div turns blue, but I want only the matched word to turn blue. How can I do this?
Here is my JS...
function init() {
window.setInterval(function() {
var div = document.getElementById("texty");
var html = div.innerHTML;
var buzzword = ["function","()","{", "}","[", "]",".getElementById", ".getElementsByClassName",".style","$"];
for(var i = 0; i < buzzword.length; i++)
{
var regex = new RegExp(buzzword[i], 'g');
html = html.replace(regex, "<span style='color:blue'>" + buzzword[i] + "</span>");
}
div.innerHTML = html;
}, 100);
}
and my HTML is this...
<div id="texty" contenteditable="true" onfocus="init()"></div>
Get the html of the div then do a regex replace and add a span around the word. Code would look something like this:
var escape= function(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
};
var div = document.getElementById("texty");
var html = div.innerHTML;
var buzzword = ["function","()","{", "}","[", "]",".getElementById", ".getElementsByClassName",".style","$"];
for(var i = 0; i < buzzword.length; i++)
{
var regex = new RegExp(escape(buzzword[i]), 'g');
html = html.replace(regex, "<span style='color:blue'>" + buzzword[i] + "</span>");
}
div.innerHTML = html;
Related
I'm making a search function for my website. So far, I've found the string the user searches for in the whole website, and I'm able to print the string and the context of the string. I have achieved this by using $.get on my HTML pages, then stripping the HTML to leave the pure text I want to search in. I then find the index of the string I'm looking for, then use substr to find the context of the input string (a few indexes ahead and behind).
Now, I need to link to the original page when a user clicks on a search result. My research says to use <a> tags, but how do I dynamically insert those into the HTML page with the index I have? And the index I have isn't even the complete page; it's stripped of tags.
These are the relevant parts of my code:
JavaScript:
function getIndicesOf(searchStr, str) { //get the indices of searchStr inside of str
var searchStrLen = searchStr.length;
if (searchStrLen == 0) {
return [];
}
var startIndex = 0, index, indices = [];
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
function search() {
obj=document.getElementById("searchButton");
obj.onclick = function() {
var searchInput = document.getElementById('searchBox').value;
var allPageContent = ['chap/telem.php', 'chap/nestor.php', 'chap/aeolus.php', 'chap/calypso.php', 'chap/circe.php', 'chap/cyclops.php', 'chap/eumaeus.php', 'chap/hades.php','chap/ithaca.php', 'chap/lestry.php', 'chap/lotus.php', 'chap/nausicaa.php', 'chap/oxen.php', 'chap/penelope.php', 'chap/proteus.php', 'chap/scylla.php', 'chap/sirens.php', 'chap/wrocks.php']; //contains all text
var allText = '';
for (var i = 0; i < allPageContent.length; i++){
$.get(allPageContent[i], function(data){
var div = document.createElement("div");
div.innerHTML = data;
//allText = div.textContent || div.innerText || ""; //gets the text to search in, stripped of html
alltext = data;
allText = allText.replace(/(\r\n\t|\n|\r\t)/gm," ");
console.log(data);
var indices = getIndicesOf(searchInput, allText); //the variable indices is the array that contains the indices of the searched text in the main text
indices.forEach(findContext);
})
}
localStorage.output = '';
function findContext(currentValue, index) {
if (currentValue <= 16) {
searchContext = "..." + allText.substr(currentValue, 100) + "...";
} else {
searchContext = "..." + allText.substr(currentValue-15, 100) + "...";
}
localStorage.output = localStorage.output + searchContext + "<br /><br />";
}
console.log(localStorage.output);
};
};
HTML:
<script>document.getElementById("output").innerHTML = localStorage.output;</script>
It's a bit confusing what you're trying to achieve, considering your HTML, but replying to this
My research says to use <a> tags, but how do I dynamically insert
those into the HTML page with the index I have?
this would do the trick
var output = document.getElementById("output");
var a = document.createElement("a");
var linkText = document.createTextNode("my linked text");
a.appendChild(linkText);
a.href = "http://example.com";
output.appendChild(a);
I need to get the sentence between tags like <p class="test" style="color:red">Hello world!</p> using regex .
Attribute of tags may differ like <p class="classname" style="color:blue">Hello world!</p>
I have code like this
var result = elements.match(/<p>(.*?)<\/p>/g).map(function(val1){
return val1.replace(/<\/?p>/g,'');
});
Use DOM instead of regex. You can use jquery to parsing string and get text of target element. Use jQuery.parseHTML() to parse string into DOM or use only jQuery().
var html = '<p class="test" style="color:red">Hello world!</p>';
console.log($(html).text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can do this by using
function findPText(str, tag) {
if (tag === void 0) {
tag = "p";
}
var fullMatch = new RegExp('\<' + tag + '.*?<\\/' + tag + '>', 'ig').exec(str);
var startMatch = new RegExp('\<' + tag + '.*?>', 'ig');
var endMatch = new RegExp('\<\/' + tag + '\s*>', 'ig');
var matches = [];
for (var index = 0; index < fullMatch.length; index++) {
var a = fullMatch[index];
matches.push(a.replace(startMatch, '').replace(endMatch, ""));
}
return matches;
}
var str = '<h1 class="test" style="color:red">Hello world</h1>bob<p class="test" style="color:red">Hello World!</p>bob';
console.log(findPText(str, "h1"));
console.log(findPText(str, "p"));
Or render it as DOM:
function findPText(str, tag) {
if (tag === void 0) {
tag = "p";
}
var myNode = document.createElement("body");
myNode.innerHTML = str;
var tags = myNode.querySelectorAll(tag);
var matches = [];
for (var index = 0; index < tags.length; index++) {
var element = tags[index];
matches.push(element.textContent);
}
return matches;
}
var str = '<h1 class="test" style="color:red">Hello <b>world</b></h1>bob<p class="test" style="color:red">Hello World!</p>bob';
console.log(findPText(str, "h1"), findPText(str, "p"));
I hope the below regex works for you. Let me know if it does.
var result = elements.match(/<p(.*?)<\/p>/g).map(function (val1) {
return val1.replace(/<\/?p.*?>/g, '');
});
.*? -> Matches all the characters(attribute properties) within the tag element.
If there are multiple tags in your element block, this will return you the array of texts. You could access them using their index
You could try something like this to get the text inside the <p> tags, depending on how your tags are formatted:
var el = '<p class="test" style="color:red">Hello world!</p>';
var re = /<p class=".*?" style="color:.*?">(.*?)<\/p>/g;
result = re.exec(el);
console.log(result[1]);
If you don't know what you're going to get inside the <p> tag, you can do something like this instead:
var el = '<p class="test" style="color:red">Hello world!</p>';
var re = /<p .*?>(.*?)<\/p>/g;
result = re.exec(el);
console.log(result[1]);
Of course, this assumes that there will never be other tags inside the <p> tag.
I've found this piece of code on the internet. It takes a sentence and makes every single word into link with this word. But it has weak side: if a sentence has HTML in it, this script doesn't remove it.
For example: it replaces '<b>asserted</b>' with 'http://www.merriam-webster.com/dictionary/<b>asserted</b>'
Could you please tell me what to change in this code for it to change '<b>asserted</b>' to 'http://www.merriam-webster.com/dictionary/asserted'.
var content = document.getElementById("sentence").innerHTML;
var punctuationless = content.replace(/[.,\/#!$%\؟^?&\*;:{}=\-_`~()”“"]/g, "");
var mixedCase = punctuationless.replace(/\s{2,}/g);
var finalString = mixedCase.toLowerCase();
var words = (finalString).split(" ");
var punctuatedWords = (content).split(" ");
var processed = "";
for (i = 0; i < words.length; i++) {
processed += "<a href = \"http://www.merriam-webster.com/dictionary/" + words[i] + "\">";
processed += punctuatedWords[i];
processed += "</a> ";
}
document.getElementById("sentence").innerHTML = processed;
This regex /<{1}[^<>]{1,}>{1}/g should replace any text in a string that is between two of these <> and the brackets themselves with a white space. This
var str = "<hi>How are you<hi><table><tr>I<tr><table>love cake<g>"
str = str.replace(/<{1}[^<>]{1,}>{1}/g," ")
document.writeln(str);
will give back " How are you I love cake".
If you paste this
var stripHTML = str.mixedCase(/<{1}[^<>]{1,}>{1}/g,"")
just below this
var mixedCase = punctuationless.replace(/\s{2,}/g);
and replace mixedCase with stripHTML in the line after, it will probably work
function stripAllHtml(str) {
if (!str || !str.length) return ''
str = str.replace(/<script.*?>.*?<\/script>/igm, '')
let tmp = document.createElement("DIV");
tmp.innerHTML = str;
return tmp.textContent || tmp.innerText || "";
}
stripAllHtml('<a>test</a>')
This function will strip all the HTML and return only text.
Hopefully, this will work for you
if you need to remove HTML tags And HTML Entities You can use
const text = '<p>test content </p><p><strong>test bold</strong> </p>'
text.replace(/<[^>]*(>|$)| ||»|«|>/g, '');
the result will be "test content test bold"
I want to create my own markdown system for my platform.
So, to allow users to make their text bold, they can wrap text in double asterisks.
Here is how I do this:
<div class="content">
The following will be bold: **I am bold**
</div>
jQuery:
function markdown(markdownable) {
var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
markdownable = markdownable.replace( bold, '<span style="font-weight:bold">$1</span>' );
return markdownable;
}
$('.content').each(function() {
var markdownable = $(this).html(),
content = markdown(markdownable);
$(this).html(content);
});
Here is a working fiddle.
Now, to my question. Whenever users add a > at the beginning of a paragraph, like this:
> Hello world, this can be a very lengthy paragraph.
Then I want to wrap that text into <blockquote>.
How can I do this?
hey i have updated your jsfiddle..
code:-
function markdown(markdownable) {
var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
markdownable = markdownable.replace(bold, '<span style="font-weight:bold">$1</span>');
if (markdownable.indexOf(">") == 0) {
markdownable = markdownable.replace(">", "<blockquote>");
markdownable += "</blockquote>";
}
return markdownable;
}
$('.content').each(function() {
var markdownable = $(this).html(),
content = markdown(markdownable);
$(this).html(content);
});
working jsfiddle example:-
http://jsfiddle.net/dwxmjkb3/2/
new Code as per request:-
function markdown(markdownableOrg) {
var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
var dataArray = markdownableOrg.split("\n");
var data = [];
for (var i = 0; i < dataArray.length; i++) {
var markdownable = dataArray[i];
markdownable = markdownable.replace(bold, '<span style="font-weight:bold">$1</span>');
if (markdownable.indexOf(">") == 0) {
markdownable = markdownable.replace(">", "<blockquote>");
markdownable += "</blockquote>";
}
data.push(markdownable)
}
return data.join("\n");
}
now above given method splits the data(each line) and checks for > and replace it with blockquote.
updated jsfiddle :-http://jsfiddle.net/dwxmjkb3/6/
thanks
Apologies for the vague title of this question!
I have the following JS, it looks for img tags with images of certain sources. It then replaces the img tag with a span so that I can replace the images/icons with iconfonts.
var paths = [
"folder%2Fadd",
"folder%2Fclear",
"folder%2Fdelete",
"folder%2Fedit",
"folder%2Fmove",
"folder%2Fsort",
];
var fullPaths = paths.map(function(x) { return "img[src*='" + x + "']"; } );
var imgs = document.querySelectorAll(fullPaths);
for (var i = 0; i < imgs.length; i++) {
var span = document.createElement("span");
span.addClass("iconfont");
span.title = imgs[i].parentNode.title;
imgs[i].parentNode.replaceChild(span, imgs[i]);
}
Everything is working nicely so far, but there is one more issue that I cannot solve.
Apart from adding a class to the span of .iconfont, I also want to add two more classes to the span - 1) the original class of the replaced img element, and 2) the name of the image source as in my array, but without the 'folder/' bit in front.
So, at the moment I have:
<img class = "tinyicon" src="******/t/edit">
and my script creates this in the DOM:
<span class = "iconfont">
But I want my script to create the following:
<span class = "iconfont tinyicon edit">
That is what I am after :)
Thanks for having a look!
var paths = [
"folder%2Fadd",
"folder%2Fclear",
"folder%2Fdelete",
"folder%2Fedit",
"folder%2Fmove",
"folder%2Fsort",
];
var fullPaths = paths.map(function(x) { return "img[src*='" + x + "']"; } );
var imgs = document.querySelectorAll(fullPaths);
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i],
iClass = img.className,
iSrc = img.src.split('/').pop(),
span = $('<span />', {'class': 'iconfont '+iClass+' '+iSrc,
title : img.parentNode.title
});
$(img).replaceWith(span);
}
Change this:
var span = document.createElement("span");
span.addClass("iconfont");
to this:
var span = document.createElement("span");
span.className = "iconfont tinyicon edit";
Your addClass() wouldn't work anyway because span is a DOM node, not a jQuery object.
var span = document.createElement("span");
var className = "iconfont " + imgs[i].className + ' ' + imgs[i].src.match(/([a-z])$/i, '')
span.className = className ;
span.title = imgs[i].parentNode.title;
imgs[i].parentNode.replaceChild(span, imgs[i]);