split a string having numbers of max characters possible in a td - javascript

I have a string
var string = "mario rossi laureato";
and I have only 15 characters available to write in a td of a table.
so the expected results should be this:
<td id="firstTD">mario rossi</td> //this td has 15 characters available
<td id="secondTD">laureato</td>
fifteenth place intersects the word "laureato", so it's calculated the excess , and takes the previous word.
another example:
var string2 = "hello my name is Paolo"
so the expected results should be this:
<td id="firstTD">hello my name</td> //this td has 15 characters available
<td id="secondTD">is Paolo</td>
fifteenth place intersects the word "is", so it's calculated the excess , and takes the previous word.
Guys any idea about this?

Try this: http://jsfiddle.net/Zh8RR/
// Sample string, to make it easy to see the cut points I've use 1-15 in hex to give us a nice easy way to see the breaks
var string = "1234567 9ABCDE 12345 7 89AB 123456 89ABC E 12 45 789A CD 123";
// Break input string up into words
var parts = string.split(' ');
var sections = [""];
var rows = 0;
// For each word
for (var i = 0; i < parts.length; ++i) {
// If it makes the section too long push it to the next section:
if (sections[rows].length + parts[i].length + 1 > 15) {
rows++;
}
// If we have no text initialise it to be the current word
if(!sections[rows]) {
sections[rows] = parts[i];
} else {
// Otherwise use a space as a separator and concat them.
sections[rows] += " " + parts[i];
}
}
// Write them out to a sample div so we can check.
$('div').html(sections.join("<br />"));

you could do:
var str = "mario rossi laureato";
var strArr = str.match(/.{1,15}/g);
console.log(strArr.length);
for(var s=0,slen=strArr.length; s < slen; s++) {
console.log(strArr[s]);
//create td and append or append strArr[s] to existing td
}

Related

How to find the first incorrect word in a document attempting to use Standard Pilish?

I am creating a GDocs Apps Script to check my document to see if it is in Standard Pilish. I'd like to have the checker return both the position of the first error and the word that is incorrect. I can get the position of the first error in pi, but since the word list does not necessarily perfectly reflect that positioning.
For example, I used a modified quote from Peter Walder: "Two mathematicians accommodatingly promenade to tavern, quest everything". The error lies in the 8th word in the list, but the 10th position in pi.
This is the script I've landed at, and I originally tried to just words[positionOne] before realizing my counting error.
function pilishTranslate() {
var doc = DocumentApp.getActiveDocument();
var text = doc.getBody().getText();
// Remove quotation marks from the text
text = text.replace(/\"/g, "");
// Replace all non-letter characters with white space
text = text.replace(/[^a-zA-Z\s]/g, " ");
// Split the text into an array of words
var words = text.split(/\s+/);
// Count word length
var wordLengths = words.map(function(word) {
return word.length;
});
// Change 10 character counts to 0
wordLengths = wordLengths.map(function(length) {
return length === 10 ? 0 : length;
});
// Join character counts into single string
var wordLengthsString = wordLengths.join('');
// Create variable for pi
var decimal15 = '314159265358979'
// Find common prefix of strings a and b.
var prefix = function(a,b){
return a && a[0] === b[0] ? a[0] + prefix(a.slice(1), b.slice(1)) : '';
};
// Find index of first difference.
var diff = function(a,b){
return a===b ? -1 : prefix(a,b).length;
};
// actual test case
var tests = [
[wordLengthsString,decimal15],
];
// find first position of error
var positionOne = tests.map(test => diff(test[0], test[1]))
console.log(positionOne);
}
function checkPilish(text) {
// Remove quotation marks from the text
text = text.replace(/\"/g, "");
// Replace all non-letter characters with white space
text = text.replace(/[^a-zA-Z\s]/g, " ");
// Split the text into an array of words
var words = text.split(/\s+/);
// Create variable for pi
var decimal15 = '314159265358979'
let pi_index = 0;
// Loop over words
for (let i = 0; i < words.length; i++) {
// convert word length to Standard Pilish digits
let length_str = String(words[i].length);
if (length_str == '10') {
word_length = '0';
}
// check if this matches the current position in pi
if (decimal15.substr(pi_index, length_str.length) != length_str) {
return [i+1, words[i]];
}
pi_index += length_str.length;
}
return [];
}
console.log(checkPilish("Two mathematicians accommodatingly promenade to tavern, quest everything"));
console.log(checkPilish("Two mathematicians accommodatingly promenade to tavern, quest all"));

Limit lines and characters per line in textarea (Javascript, jQuery)

What I need is to be able to limit the number of lines in a textarea. And to limit the number of characters in each line (force adding a newline when maximum number of characters has been added.
I am not interested in the "rows" and "cols" attributes. They do not work.
Also, I would like to have it working even if the user cuts or pastes something, or if he returns to a line and modifies it.
Not sure if this is an overly complex way of doing it but you can loop through the textarea and add a newline every X characters. This solution won't allow users to insert their own line breaks (it strips off any existing line breaks) .
<textarea onkeyup="formatTextArea(this)"></textarea>
<script type="text/javascript">
function formatTextArea(myArea)
{
//strip off any line breaks first
var str = myArea.value.replace(/\n|\r/g, "");
var result = '';
var i = 0
var formattedText = '';
//number of lines needed
var limit = 5
// number of characters
var limitPerLine = 20;
// loop through the text, adding a new line every limitPerLine characters
// stop after limit lines
while (str.length > 0 && i < limit)
{
i++;
formattedText += str.substring(0, limitPerLine);
str = str.substring(limitPerLine);
//only add a new line if we're not at the end of the content
if(str.length > 0 && i < limit)
{
formattedText += '\n';
}
}
myArea.value = formattedText;
}
</script>

Add Text At Location from indexOf

I am working on inserting text to the bottom of certain wordpress posts based on the amount of times a string occurs. I've managed to add the text to the bottom with append but instead I would like to insert at a specific location using indexOf.
here is the original text:
if ($('body').hasClass("single-post")){
var count = 0;
var cSearch = $('body').text();
var words = cSearch.indexOf('Words To Find')
while (words !== -1){
count++;
words = cSearch.indexOf('Words To Find', words + 1);
}
if( count >= 2){
$('.entry-content').append('<br><br>Sample Text');
}
}
Here is how I will get the location I want to insert before:
var insertLocation = cSearch.indexOf('Show what ya');
How can I splice the "Sample Text" into the location specified with insertLocation?
I found a bit about using polyfil for .splice but I'm not sure it works for this. Using it such as:
$(cSearch).splice( insertLocation, -1 ).text( "Sample Text" );
Can someone suggest a way to do this? Thanks!
Try creating variables representing total matches , indexOf() match plus matched text .length , using .slice() to insert original text before second match , new text ti insert , followed by remainder of original text
var text = $("div").text(),
match = "Words To Find",
txt = " Sample Text ",
matches = 0,
n = 0,
// `max` : total number of `matches` before inserting `txt`
max = 2;
while (matches < max) {
if (text.indexOf(match, n) !== -1) {
i = text.indexOf(match, n);
n = i + match.length;
++matches
}
}
// insert `re` after second match of `"Words To find"`
var re = text.slice(0, i + match.length) + txt;
$("div").text(re + text.slice(i));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body>
<div>Words To Find abc def Words To Find ghi Words To Find</div>
</body>

Extract keyphrases from text (1-4 word ngrams)

What's the best way to extract keyphrases from a block of text? I'm writing a tool to do keyword extraction: something like this. I've found a few libraries for Python and Perl to extract n-grams, but I'm writing this in Node so I need a JavaScript solution. If there aren't any existing JavaScript libraries, could someone explain how to do this so I can just write it myself?
I like the idea, so I've implemented it: See below (descriptive comments are included).
Preview at: https://jsfiddle.net/WsKMx
/*#author Rob W, created on 16-17 September 2011, on request for Stackoverflow (http://stackoverflow.com/q/7085454/938089)
* Modified on 17 juli 2012, fixed IE bug by replacing [,] with [null]
* This script will calculate words. For the simplicity and efficiency,
* there's only one loop through a block of text.
* A 100% accuracy requires much more computing power, which is usually unnecessary
**/
var text = "A quick brown fox jumps over the lazy old bartender who said 'Hi!' as a response to the visitor who presumably assaulted the maid's brother, because he didn't pay his debts in time. In time in time does really mean in time. Too late is too early? Nonsense! 'Too late is too early' does not make any sense.";
var atLeast = 2; // Show results with at least .. occurrences
var numWords = 5; // Show statistics for one to .. words
var ignoreCase = true; // Case-sensitivity
var REallowedChars = /[^a-zA-Z'\-]+/g;
// RE pattern to select valid characters. Invalid characters are replaced with a whitespace
var i, j, k, textlen, len, s;
// Prepare key hash
var keys = [null]; //"keys[0] = null", a word boundary with length zero is empty
var results = [];
numWords++; //for human logic, we start counting at 1 instead of 0
for (i=1; i<=numWords; i++) {
keys.push({});
}
// Remove all irrelevant characters
text = text.replace(REallowedChars, " ").replace(/^\s+/,"").replace(/\s+$/,"");
// Create a hash
if (ignoreCase) text = text.toLowerCase();
text = text.split(/\s+/);
for (i=0, textlen=text.length; i<textlen; i++) {
s = text[i];
keys[1][s] = (keys[1][s] || 0) + 1;
for (j=2; j<=numWords; j++) {
if(i+j <= textlen) {
s += " " + text[i+j-1];
keys[j][s] = (keys[j][s] || 0) + 1;
} else break;
}
}
// Prepares results for advanced analysis
for (var k=1; k<=numWords; k++) {
results[k] = [];
var key = keys[k];
for (var i in key) {
if(key[i] >= atLeast) results[k].push({"word":i, "count":key[i]});
}
}
// Result parsing
var outputHTML = []; // Buffer data. This data is used to create a table using `.innerHTML`
var f_sortAscending = function(x,y) {return y.count - x.count;};
for (k=1; k<numWords; k++) {
results[k].sort(f_sortAscending);//sorts results
// Customize your output. For example:
var words = results[k];
if (words.length) outputHTML.push('<td colSpan="3" class="num-words-header">'+k+' word'+(k==1?"":"s")+'</td>');
for (i=0,len=words.length; i<len; i++) {
//Characters have been validated. No fear for XSS
outputHTML.push("<td>" + words[i].word + "</td><td>" +
words[i].count + "</td><td>" +
Math.round(words[i].count/textlen*10000)/100 + "%</td>");
// textlen defined at the top
// The relative occurence has a precision of 2 digits.
}
}
outputHTML = '<table id="wordAnalysis"><thead><tr>' +
'<td>Phrase</td><td>Count</td><td>Relativity</td></tr>' +
'</thead><tbody><tr>' +outputHTML.join("</tr><tr>")+
"</tr></tbody></table>";
document.getElementById("RobW-sample").innerHTML = outputHTML;
/*
CSS:
#wordAnalysis td{padding:1px 3px 1px 5px}
.num-words-header{font-weight:bold;border-top:1px solid #000}
HTML:
<div id="#RobW-sample"></div>
*/
I do not know such a library in JavaScript but the logic is
split text into array
then sort and count
alternatively
split into array
create a secondary array
traversing each item of the 1st array
check whether current item exists in secondary array
if not exists
push it as a item's key
else
increase value having a key = to item sought.
HTH
Ivo Stoykov
function ngrams(seq, n) {
to_return = []
for (let i=0; i<seq.length-(n-1); i++) {
let cur = []
for (let j=i; j<seq.length && j<=i+(n-1); j++) {
cur.push(seq[j])
}
to_return.push(cur.join(''))
}
return to_return
}
> ngrams(['a', 'b', 'c'], 2)
['ab', 'bc']

How to get text between commas in Javascript?

I have an input field with comma separated values. I want to get the text between commas so that I can add a suggestion for each element. I found that I can get the cursor position using the value of the first child, how do I get only the text between commas?
Edit: split will get value of an array, but I wish to know which word my cursor is on (between the commas). firstChild.nodevalue gives me the caret position. I would like the word at the caret position. Example: apple, orange, banana ... if my cursor was between the o and the range, it might give the suggestion orange, oranges, etc. If I somehow can get a function to return "orange" if my cursor is somewhere on the word, then I can compare it to a suggestion array.
This should do the trick...
var pos = 11; // use w/e you need to get the position.
var value = "apple, orange, banana";
var array = value.split(',');
var item = null;
var current_length = 0;
for(var i=0;i<array.length;i++) {
current_length += array[i].length;
if(pos < (current_length + i)) {
item = array[i].replace(/\s/ig, "");
break;
}
}
alert(item) // -> "orange"
Or without using split:
var pos = 11; // use w/e you need to get the position.
var value = "apple, orange, banana";
var item = '';
var len = value.length;
var pointer=pos;
while (true) { var char=value.substr(pointer,1); if (pointer-->=0 && char!=',') item = char + item; else break }
pointer=pos+1;
while (true) { var char=value.substr(pointer,1); if (pointer++<len && char!=',') item += char; else break}
alert(item) // -> "orange"

Categories