Highlight Text in textarea if not in the array using highlighttextarea plugin - javascript

I am using jQuery highlightTextarea plugin to highlight words in an html textarea.
jQuery highlightTextarea
It currently highlights those words IN the array,
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo', 'stackoverflow'];
But what I want to do is highlight all words which are NOT IN the array. Is there any way I can do this?
My jsfiddle: http://jsfiddle.net/fr7wb2b4/11/

Stupid I have not tought of it, what about this:
$(document).ready(function () {
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo', 'stackoverflow'];
$('#textarea').highlightTextarea({
words: [
{ color : '#F00',
words : ['(.+)']
}, // Make everything highlighted
{ color : '#FFF',
words : words
} // Make white what matched
]
});
});
Fiddle with it over here
You could also use words : ['(\\w+)'] to only highlight words initially

You can take a look at the library source, the highlight code: https://github.com/mistic100/jquery-highlighttextarea/blob/master/jquery.highlighttextarea.js#L67
The snippet that does the actual highlighting is:
$.each(this.settings.words, function(color, words) {
text = text.replace(
new RegExp(that.spacer+'('+ words.join('|') +')'+that.spacer, that.regParam),
'<mark style="background-color:'+ color +';">$1</mark>'
);
});
So you can replace the highlight function with your own function, and do whatever logic you choose for highlighting (hurray for open source!)
For example you can copy-paste of the entire function just replace the $.each(words... loop with something along:
var replaced = '',
tokens = text.split(' ');
$.each(tokens, function(ind, token) {
if (this.settings.words.indexOf(token) != -1) {
// this token in the text is part of the 'words' - do not highlight
replaced += token;
}
else {
// this token isn't part of the words - highlight it
replaced += '<span style="...">'+token+'</span>';
}
replaced += ' ';
}
text = replaced;

Related

Get the count of words in tinymce

I have a word count div outside the tinymce which shows the word count but not using the wordCount plugin but using regex to count the words.
But this count is not showing correct value when i add bullet or apply bold to the already typed text[It is showing count as 3 while i have entered only one word at the time of using bullet and increases the count by 2 while highlighting the already typed text]
Can any one can suggest what to do in the regex to get correct count when using the bold or,italic,underline or bullets or using wordCount plugin to use it's output outside the stauts bar[In this case in my word count div]
Here is the code :
tinymceConfig = {
mode:"exact",
elements:"essay",
menubar: false,
statusbar: false,
plugins: "autoresize",
content_css : '../../theme/css/Language/editor.css',
toolbar : "bold italic underline bullist",
resize:"height",
autoresize_max_height: 325,
setup : function(editor) {
if ($('#essay').prop('readonly')) {
editor.settings.readonly = true;
}
editor.on('keydown', function (evt) {
var wordCount = 0;
var valid_keys = [8, 46];
text = editor.getContent().replace(/(< ([^>]+)<)/g, '').replace(/\s+/g, ' ');
text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
wordCount = text.split(' ').length-1;
if(wordCount >= Helpers.constants.MAX_WORDS && valid_keys.indexOf(evt.keyCode) == -1)
{
evt.preventDefault();
Helpers.prompt('You have reached the maximum word limit.');
//evt.stopPropagation();
return false;
}
});
editor.on('keyup', function (evt) {
var text = '';
clearTimeout(saveEssayIntervalId);
saveEssayIntervalId = setTimeout(function() {
saveEssay('silent');
}, 3000);
text = editor.getContent().replace(/(< ([^>]+)<)/g, '').replace(/\s+/g, ' ');
text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var wordCount = text.split(' ').length;
$("#essayContainer .textAreaAfter").html("[ Words entered: "+wordCount+" ]");
});
} };
tinyMCE.init(tinymceConfig);
You can get the current word count from TinyMCE's WordCount plugin - you should not need to calculate this yourself.
theEditor = tinymce.activeEditor;
wordCount = theEditor.plugins.wordcount.getCount();
If you have an old tinyMCE version, you may not have the getCount() function, in this case you can write, for the active editor (else pass on the editor's object):
var editor = tinyMCE.activeEditor,
words = editor.plugins.wordcount._getCount(editor);

Function does not work on second occurence?

I am trying to change the color of multiple texts to a certain color by using this code:
var search = "bar";
$("div:contains('"+search+"')").each(function () {
var regex = new RegExp(search,'gi');
$(this).html($(this).text().replace(regex, "<span class='red'>"+search+"</span>"));
});
However, the code does not work a second time, and I am not sure why--it only changes the newest occurrence of the code.
Here is a JSFiddle using it twice where it is only changing the 2nd occurrence: http://jsfiddle.net/PELkt/189/
Could someone explain why it does not work on the 2nd occurrence?
Could someone explain why it does not work on the 2nd occurrence?
By calling .text() you are removing all the HTML markup, including the <span>s you just inserted.
This is the markup after the first replacement:
<div id="foo">this is a new <span class='red'>bar</span></div>
$(this).text() will return the string "this is a new bar", in which replace "new" with a <span> ("this is a <span class='red'>new</span> bar") and set it as new content of the element.
In order to do this right, you'd have to iterate over all text node descendants of the element instead, and process them individually. See Highlight a word with jQuery for an implementation.
It was easy to fix your jsfiddle. Simply replace both .text() with .html() & you'll see that it highlights new & both bars in red.
jQuery's .text() method will strip all markup each time that it's used, but what you want to do is use .html() to simply change the markup which is already in the DOM.
$(document).ready(function () {
var search = "bar";
$("div:contains('"+search+"')").each(function () {
var regex = new RegExp(search,'gi');
$(this).html($(this).html().replace(regex, "<span class='red'>"+search+"</span>"));
});
search = "new";
$("div:contains('"+search+"')").each(function () {
var regex = new RegExp(search,'gi');
$(this).html($(this).html().replace(regex, "<span class='red'>"+search+"</span>"));
});
});
Here is another way of doing it that will allow you to continue using text if you wish
function formatWord(content, term, className){
return content.replace(new RegExp(term, 'g'), '<span class="'+className+'">'+term+'</span>');
}
$(document).ready(function () {
var content = $('#foo').text();
var change1 = formatWord(content, 'bar', 'red'),
change2 = formatWord(change1, 'foo', 'red');
alert(change2);
$('body').html(change2);
});
http://codepen.io/nicholasabrams/pen/wGgzbR?editors=1010
Use $(this).html() instead of $(this).text(), as $.fn.text() strips off all the html tags, so are the <span class="red">foo</span> stripped off to foo.
But let's say that you apply same highlight multiple times for foo, then I would suggest that you should create a class similar to this to do highlighting
var Highlighter = function ($el, initialArray) {
this._array = initialArray || [];
this.$el = $el;
this.highlight = function (word) {
if (this.array.indexOf(word) < 0) {
this.array.push(word);
}
highlightArray();
}
function highlightArray() {
var search;
// first remove all highlighting
this.$el.find("span[data-highlight]").each(function () {
var html = this.innerHTML;
this.outerHTML = html;
});
// highlight all here
for (var i = 0; i < this._array.length; i += 1) {
search = this._array[i];
this.$el.find("div:contains('"+search+"')").each(function () {
var regex = new RegExp(search,'gi');
$(this).html($(this).html().replace(regex, "<span data-highlight='"+search+"' class='red'>"+search+"</span>"));
});
}
}
}
var highlighter = new HighLighter();
highlighter.highlight("foo");

Add ">" symbol at front of each textarea line using jquery

i don't know how to add this symbol '*' at front of every line of textarea. I have a hidden textarea which is #repmsg, and assume that in that box have 3 line. I want when user click #modquote, the confirm box will appear, and when user click OK, inside the textarea#modrepmsg will display
>line1
>line2
>line3
Here my jquery code
$( '#modquote')
.click(function() {
if (confirm('ausdhkajsdhskj?'))
{
var comment = $('#repmsg').val();
var regex = /<br\s*[\/]?>/gi;
var repmsg = comment.replace(regex, "")
var quote = '>' + repmsg;
$('textarea#modrepmsg').val(quote);
}
});
Thanks for helping.
Something like:
$('#modrepmsg').val(function() {
return $('#repmsg').val().split('\n').map(function(line) {
return '>'+line;
}).join('\n');
});
Demo: http://jsfiddle.net/cm7d6/
you could replace \r\n or what ever return / linebreak is in the text area and replace with \r>
then preceed the content with >
You want to use a regex that gets the beginning or a text line so ^ should be used
$( '#modquote')
.click(function() {
if (confirm('ausdhkajsdhskj?'))
{
var comment = $('#repmsg').val();
var repmsg = comment.replace("/^/g", ">")
$('textarea#modrepmsg').val(repmsg );
}
});

Get certain text replace it and wrap it in span?

I have following html<p class="get">This is some content.</p> what I would like to do is to make it like this:<p class="get">This is <span>some</span> content.</p>. To accomplish this I know I should: 1. get my certain text (done that...)
2. Wrap my text in span (done that also...)
3. replace my text with text that contains my span (haven't done it)
My problem is step 3 I just can't figure it out. So how can I replace my "old" text with new one?Thank you guys!!!
Fiddle here
My code looks like this:
$(document).ready(function(){
//get the whole text
var ptext = $(".get").text().split(" ");
var myText = ptext[2];
//alert(ptext[2])
//alert(myText);
if($('.get').text().contains(myText)){
//$('<span>'+myText+'</span>').appendTo($('.get'));
}
else{
alert('no text');
}
});
var word = "some",
regex = new RegExp("\\b" + word + "\\b", "g");
$(".get").html(function(i, html) {
return html.replace(regex, "<span>$&</span>");
});
DEMO: http://jsfiddle.net/V7Wnk/1/
$('.get').html(function (i, v) {
return v.replace('some', '<span>some</span>');
});
$('.get').html($(".get").html().replace("some","<span> some </span>"));

jQuery putting content of a paragraph in a textarea

I tried to do this for replacing a paragraph with a text area with the same content.
function edit() {
var wdith = $("p").css('width')
$("p:first").replaceWith("<textarea class='edit'>" + $("p:first").text() + "</textarea>")
$(".edit").css("width", wdith)
}
$("#replace").click(edit);
Demo
But it doesn't work correctly. There are spaces before and after the text.
How do I fix it?
You script is doing as it says on the tin. You're getting spaces because you have spaces and line breaks within your <p> tags.
To remove the text formatting, try this: http://jsfiddle.net/z9xCm/18/
function edit() {
var wdith = $("p").css('width');
var p = $("p:first");
var t = p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim();
p.replaceWith("<textarea class='edit'>" + t + "</textarea>")
$(".edit").css("width", wdith)
}
$("#replace").click(edit);
First, we remove the line breaks, then removed multiple repeated spaces, then trim spaces at the beginning and end of the text.
Somewhat off topic, but that can also be rewritten as : http://jsfiddle.net/z9xCm/52/
$("#replace").click(function() {
var p = $("p:first");
p.replaceWith($("<textarea/>", {
"class": "edit",
"text": p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim(),
"css": { "width": p.css('width') }
}));
});
Here's the same thing, but in a less compact and commented form.
$("#replace").click(function() { /* assign anonymous function to click event */
var p = $("p:first"); /* store reference to <p> element */
/* get p.text() without the formatting */
var t = p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim();
/* create new textarea element with additional attributes */
var ta = $("<textarea/>", {
"class": "edit",
"text": t,
"css": {
"width": p.css('width')
}
});
p.replaceWith(ta); /* replace p with ta */
});
Note that the $("...", {...}) syntax for creating new elements with attributes was only introduced in jquery 1.4.
You can use the method $.trim() to remove the spaces at the begin and end:
$.trim($("p:first").text());
You could trim each line manually: http://jsfiddle.net/z9xCm/14/.
function edit() {
var wdith = $("p").css('width');
var spl = $("p").text().split("\n");
spl = spl.map(function(v) {
return v.trim();
});
var txt = spl.join(" ").trim();
$("p:first").replaceWith("<textarea class='edit'>" + txt + "</textarea>")
$(".edit").css("width", wdith)
}
$("#replace").click(edit);
You're paragraph has leading spaces at the start of each line. These are remaining when you convert it to a textarea. So remove the spaces from the <p> block to fix the issue.
Updated demo
Also remove line breaks if you don't want them to remain.
Updated demo without line breaks either
Use the following with a regular expression replacement (updated Fiddle):
function edit() {
var wdith = $("p").css('width')
$("p:first").replaceWith("<textarea class='edit'>" + $("p:first").text().replace(/[\n\r](\s*)/g," ").trim() + "</textarea>")
$(".edit").css("width", width)
}
$("#replace").click(edit);

Categories

Resources