jQuery counting spaces - javascript

Gretings, I have a bit complicated issue. I'm appending text to textarea with javascript. My question is - how to count, how many spaces are on the text area location, where the mouse is clicked? I'm appending text like this:
function typeInTextarea(el, newText) {
var start = el.prop("selectionStart")
var end = el.prop("selectionEnd")
var text = el.val()
var before = text.substring(0, start)
var after = text.substring(end, text.length)
el.val(before + newText + after)
el[0].selectionStart = el[0].selectionEnd = start + newText.length
el.focus()
}
$(".containeris").on("click", function() {
typeInTextarea($("#html_content"), '<div class="container">\n\n</div>')
return false
})
So the problem is, it starts appending text exactly, where mouse is clicked, but i want to make sure, that closing div, which is being printed in new line, would have same number of spaces in front of it as starting line, to keep indentation. Is it possible to achieve?

Solution was simpy to count tabulations as symbols.

Related

How Do I Cut Off the End of AJAX Loaded Text?

I am trying to cut off (truncate) extra characters off of the end of an AJAX-loaded element with text in it. Here's how I'm loading the element:
$("#destinationElement").load("/sourcePageName .classWithinPage");
I would like to limit the length of the text inside of #destinationElement to 140 characters, but the text within .classWithinPage may be longer, so I need to cut it off after that point somehow. I'd also like to add an ellipses afterwards, if possible.
I tried adding a function afterwards that would do this (see the following) but it didn't seem to work, and I would prefer it ran before the text was added to #destinationElement, so that the script would do its work before the text displayed.
var maxLength = 140;
function shorten(element) {
var text = $(element).text();
if(text.length > maxLength){
text = text.substring(0, maxLength);
var lastIndex = text.lastIndexOf(" ");
text = text.substring(0, lastIndex) + '...';
}
$(element).text(text);
};
shorten('#destinationElement');
^^ That didn't work. Plus, I think I should probably be adding in my function as a part of the jQuery load function I have up above, I'm just not sure how.
How do I truncate the text that's being loaded to 140 characters before it appears on-screen?
Use the $.get method instead if you want to modify the data
$.get('/sourcePageName', function(data) {
var text = $('<div />', {html : data}).find('.classWithinPage').text();
if (text.length > 140) {
text = text.slice(0, 140) + '...';
}
$("#destinationElement").text(text);
});

How Do I Add Ellipses to Text

I am trying to create a function that will take an element's text, cut off any characters beyond 80, and add an ellipses if necessary. Here's my code so far:
var maxLength = 80;
function shorten(element) {
var text = $('#' + element).text();
var ret = text;
if (text.length > maxLength) {
text = text.substr(0,maxLength-3) + "...";
}
$('#' + element).text(text);
}
shorten('slide1');
So, the function should take the element, remove extra text off the end, add an ellipses, and then replace the old text in the element with the new string I've just created.
When I run the function, I don't get any errors, but it doesn't actually cut off the text as it should. Why is this?
var text = "Some Text Goes Here. La La La La!";
var textLength = 10; // Number of characters to cut off after
function shorten(text, textLength){
if(text.length > textLength){
text = text.substring(0, textLength) + '…';
}
return text;
}
var shortText = shorten(text, textLength);
Also, using the HTML character for ellipsis is better than using three periods.
I've added a Codepen showing the code working. Additionally, I added a function spaceShorten that will split your text at the last occurrence of a space that is less than the length provided, so you don't split the text mid word.
http://codepen.io/supah_frank/pen/EaYzNz

Position changes every time with window.getSelection()

Can anyone help me? I got these codes here https://stackoverflow.com/a/17836828/2338164
$(document).on("mouseup",".wrap",function(){
var highlight = window.getSelection();
if(highlight.toString().length>=1){
var spn = '<span class="highlight">' + highlight + '</span>';
var text = $(this).text();
var range = highlight.getRangeAt(0);
var startText = text.substring(0, range.startOffset);
var endText = text.substring(range.endOffset, text.length);
$('#q3txt').append(range.startOffset+"<br>");
$(this).html(startText + spn + endText);
}
});
I tried to use it and it's working fine, until you highlight again...
Here's a link http://jsfiddle.net/AN76g/.
What im trying to do is... user will highlight a block then wrap it in span, but if the user made a mistake and tries to highlight again, the span is removed and will try to wrap the new highlighted text. But either the position changes or parts of the text are being appended.
See this update: jsfiddle.
First, on the mousedown, you can unwrap the span as so:
$(document).on("mousedown",".wrap",function(){
$('.highlight').contents().unwrap();
});
Secondly, the problem with using the range.startOffset and range.endOffset is that you the start is relative to the containing element which could be the highlight span which causes you to replace the incorrect text on subsequent selections. Instead, replace the selection with the span as so:
$(document).on("mouseup",".wrap",function(){
var highlight = window.getSelection();
if(highlight.toString().length>=1){
var range = highlight.getRangeAt(0);
var selectionContents = range.extractContents();
var spn = document.createElement("span");
spn.className='highlight';
spn.appendChild(selectionContents);
range.insertNode(spn);
highlight.removeAllRanges();
}
});
Information from MDN Range.startOffset, specifically:
the startContainer is a Node of type Text, Comment, or CDATASection, then the offset is the number of characters from the start of the startContainer to the boundary point of the Range. For other Node types, the startOffset is the number of child nodes between the start of the startContainer and the boundary point of the Range.
Also, this answer.

Getting the last entered word from a contentEditable div

I have a div tag with contenteditable set to true.
I am trying to find out the last entered word in the div.
For example, if I type in This is a test and I hit a space, I want to be able to get the word test
I want to be able to use this logic so that I can test each word being typed (after the space is pressed).
It would be great if someone could help me with this.
An easy solution would be the following
var str = "This is a test "; // Content of the div
var lastWord = str.substr(str.trim().lastIndexOf(" ")+1);
trim might need a shim for older browsers. (.replace(/\s$/,""))
To strip punctuation like " Test!!! " you could additionally do a replace like following:
lastWord.replace(/[\W]/g,"");
You might want to do a more specific definition of the characters to omit than \W, depending on your needs.
If you want to trigger your eventhandler also on punctuation characters and not only on space, the last replace is not needed.
You first have to know when the content is edited. Using jQuery, that can be done with
​$("div").on("keyup", function(){ /* code */ });
Then, you'll have to get the whole text and split it into words
var words = $(this).text().trim().split(' ');
And getting the last word is as complicated as getting the last element of the words array.
Here's the whole code
HTML
​<div contenteditable="true">Add text here</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
JavaScript (using jQuery)
​
$("div").on("keyup", function(){
var words = $(this).text().trim().split(' '),
lastWord = words[words.length - 1];
console.log(lastWord);
});​​​​​​​
Demo
This is the ultimate way:
// listen to changes (do it any way you want...)
document.querySelectorAll('div')[0].addEventListener('input', function(e) {
console.log( getLastWord(this.textContent) );
}, false);
function getLastWord(str){
// strip punctuations
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\_`~()]/g,' ');
// get the last word
return str.trim().split(' ').reverse()[0];
}
DEMO PAGE
You can try this to get last word from a editable div.
HTML
<div id='edit' contenteditable='true' onkeypress="getLastWord(event,this)">
</div>
JS
function getLastWord(event,element){
var keyPressed = event.which;
if(keyPressed == 32){ //Hits Space
var val = element.innerText.trim();
val = val.replace(/(\r\n|\n|\r)/gm," ");
var idx = val.lastIndexOf(' ');
var lastWord = val.substring(idx+1);
console.log("Last Word " + lastWord);
}
}
Try this link http://jsfiddle.net/vV2mN/18/

Clean Microsoft Word Pasted Text using JavaScript

I am using a 'contenteditable' <div/> and enabling PASTE.
It is amazing the amount of markup code that gets pasted in from a clipboard copy from Microsoft Word. I am battling this, and have gotten about 1/2 way there using Prototypes' stripTags() function (which unfortunately does not seem to enable me to keep some tags).
However, even after that, I wind up with a mind-blowing amount of unneeded markup code.
So my question is, is there some function (using JavaScript), or approach I can use that will clean up the majority of this unneeded markup?
Here is the function I wound up writing that does the job fairly well (as far as I can tell anyway).
I am certainly open for improvement suggestions if anyone has any. Thanks.
function cleanWordPaste( in_word_text ) {
var tmp = document.createElement("DIV");
tmp.innerHTML = in_word_text;
var newString = tmp.textContent||tmp.innerText;
// this next piece converts line breaks into break tags
// and removes the seemingly endless crap code
newString = newString.replace(/\n\n/g, "<br />").replace(/.*<!--.*-->/g,"");
// this next piece removes any break tags (up to 10) at beginning
for ( i=0; i<10; i++ ) {
if ( newString.substr(0,6)=="<br />" ) {
newString = newString.replace("<br />", "");
}
}
return newString;
}
Hope this is helpful to some of you.
You can either use the full CKEditor which cleans on paste, or look at the source.
I am using this:
$(body_doc).find('body').bind('paste',function(e){
var rte = $(this);
_activeRTEData = $(rte).html();
beginLen = $.trim($(rte).html()).length;
setTimeout(function(){
var text = $(rte).html();
var newLen = $.trim(text).length;
//identify the first char that changed to determine caret location
caret = 0;
for(i=0;i < newLen; i++){
if(_activeRTEData[i] != text[i]){
caret = i-1;
break;
}
}
var origText = text.slice(0,caret);
var newText = text.slice(caret, newLen - beginLen + caret + 4);
var tailText = text.slice(newLen - beginLen + caret + 4, newLen);
var newText = newText.replace(/(.*(?:endif-->))|([ ]?<[^>]*>[ ]?)|( )|([^}]*})/g,'');
newText = newText.replace(/[·]/g,'');
$(rte).html(origText + newText + tailText);
$(rte).contents().last().focus();
},100);
});
body_doc is the editable iframe, if you are using an editable div you could drop out the .find('body') part. Basically it detects a paste event, checks the location cleans the new text and then places the cleaned text back where it was pasted. (Sounds confusing... but it's not really as bad as it sounds.
The setTimeout is needed because you can't grab the text until it is actually pasted into the element, paste events fire as soon as the paste begins.
How about having a "paste as plain text" button which displays a <textarea>, allowing the user to paste the text in there? that way, all tags will be stripped for you. That's what I do with my CMS; I gave up trying to clean up Word's mess.
You can do it with regex
Remove head tag
Remove script tags
Remove styles tag
let clipboardData = event.clipboardData || window.clipboardData;
let pastedText = clipboardData.getData('text/html');
pastedText = pastedText.replace(/\<head[^>]*\>([^]*)\<\/head/g, '');
pastedText = pastedText.replace(/\<script[^>]*\>([^]*)\<\/script/g, '');
pastedText = pastedText.replace(/\<style[^>]*\>([^]*)\<\/style/g, '');
// pastedText = pastedText.replace(/<(?!(\/\s*)?(b|i|u)[>,\s])([^>])*>/g, '');
here the sample : https://stackblitz.com/edit/angular-u9vprc
I did something like that long ago, where i totally cleaned up the stuff in a rich text editor and converted font tags to styles, brs to p's, etc, to keep it consistant between browsers and prevent certain ugly things from getting in via paste. I took my recursive function and ripped out most of it except for the core logic, this might be a good starting point ("result" is an object that accumulates the result, which probably takes a second pass to convert to a string), if that is what you need:
var cleanDom = function(result, n) {
var nn = n.nodeName;
if(nn=="#text") {
var text = n.nodeValue;
}
else {
if(nn=="A" && n.href)
...;
else if(nn=="IMG" & n.src) {
....
}
else if(nn=="DIV") {
if(n.className=="indent")
...
}
else if(nn=="FONT") {
}
else if(nn=="BR") {
}
if(!UNSUPPORTED_ELEMENTS[nn]) {
if(n.childNodes.length > 0)
for(var i=0; i<n.childNodes.length; i++)
cleanDom(result, n.childNodes[i]);
}
}
}
This works great to remove any comments from HTML text, including those from Word:
function CleanWordPastedHTML(sTextHTML) {
var sStartComment = "<!--", sEndComment = "-->";
while (true) {
var iStart = sTextHTML.indexOf(sStartComment);
if (iStart == -1) break;
var iEnd = sTextHTML.indexOf(sEndComment, iStart);
if (iEnd == -1) break;
sTextHTML = sTextHTML.substring(0, iStart) + sTextHTML.substring(iEnd + sEndComment.length);
}
return sTextHTML;
}
Had a similar issue with line-breaks being counted as characters and I had to remove them.
$(document).ready(function(){
$(".section-overview textarea").bind({
paste : function(){
setTimeout(function(){
//textarea
var text = $(".section-overview textarea").val();
// look for any "\n" occurences and replace them
var newString = text.replace(/\n/g, '');
// print new string
$(".section-overview textarea").val(newString);
},100);
}
});
});
Could you paste to a hidden textarea, copy from same textarea, and paste to your target?
Hate to say it, but I eventually gave up making TinyMCE handle Word crap the way I want. Now I just have an email sent to me every time a user's input contains certain HTML (look for <span lang="en-US"> for example) and I correct it manually.

Categories