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"
Related
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"));
How to get duplicate character in JavaScript,
As like input:
aaabcccdeffa
Output:
a4bc3def2
Try this:
var str = "aaabcccdeffa"; // Original string
// We are going to create a key-value array to store the number of occurance
// per letter (eg. 'a' : 4, 'b' : 1 etc.)
var store = {};
// Next we loop through each letter in the string
for (var a in str) {
if (store[str[a]] == undefined) { // If this letter has not ben found before, we set the count to 1 (first occurance)
store[str[a]] = 1;
}
else { // else if the letter has been found, we increase the count by one
store[str[a]] += 1;
}
}
// At this point, we have a key value array that contains the count of each letter
// Next, we loop through this array to generate the new string
var newStr = ''; // Initialise new string
for (var char in store) {
newStr += char; // append the letter to the string
if (store[char] > 1) {
newStr += store[char]; // If the count is more than one, we want to show the number too, so we append the number to the string
}
}
Output will be in newStr
you can use a HashTable, which in javascript is done through an Object. This code works
function duplicateCharacters(str) {
//Create an empty object
var hashTable = {};
for(var i = 0; i < str.length; i++){
//Check if the character has already been registered
//If false, register it and link a 1 to it
//If true, increment the integer linked to it
if (hashTable.hasOwnProperty(str[i]))
hashTable[str[i].toString()]++;
else
hashTable[str[i].toString()] = 1;
}
var output = "";
//Go through the hashTable
for(var key in hashTable) {
//Concatenate the key
output += key.toString();
//If the character only appeared once, do not add it
if(hashTable[key] != 1)
output += hashTable[key].toString()
}
return output;
}
Here is the reference code which uses both jquery and Regular expression for calculating the frequency of the character.
// Variable Declaration with Source text
var sourceText="aaabcccdeffa";
var resultText="";
// Splitting the source text to array
var sourceTextArray=sourceText.split("");
var uniqueText = [];
//Fetches Unique text from sourceTextArray in order
$.each(sourceTextArray, function(i, el){
if($.inArray(el, uniqueText) === -1) uniqueText.push(el);
});
//Iteration with unique text array
$.each(uniqueText, function(i, el){
//Regular Expression approach to calculate frequency of character with source text
resultText+=(sourceText.match(new RegExp(el, "g")) || []).length>1?el+(sourceText.match(new RegExp(el, "g")) || []).length:el;
});
alert(resultText);
Working Example Here
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
}
In JS I have a text line and I want to get the index of the first occurrence of an empty space.
For example, this is my line:
gram somethin b
And this is my code:
index = line.indexOf(" ");
if (index == -1)
index = line.indexOf("\u00a0");
The problem here is that the result of the code is 13, but it should be 4.
Why doesnt it recognize the empty space after 'gram' as empty space? How can I check?
Also can Use Here ASCII character
ASCII code 32 for Space
var line = "gram somethin b";
var FirstSpaceIndex;
for (var i = 0; i < line.length; i++)
{
if(line.charCodeAt(i) == 32)
{
FirstSpaceIndex = i;
break;
}
}
alert(FirstSpaceIndex);
I want to ignore counting the length of characters in the text if there are special codes inside in textarea. I mean not to count the special codes characters in the text. I use special codes to define inputing smileys in the text. I want to count only the length of the text ignoring special code.
Here is my approximate code I tried to write, but can't let it work:
// smileys
// =======
function smileys(){
var smile = new Array();
smile[0] = "[:rolleyes:]";
smile[1] = "[:D]";
smile[2] = "[:blink:]";
smile[3] = "[:unsure:]";
smile[4] = "[8)]";
smile[5] = "[:-x]";
return(smile);
}
// symbols length limitation
// =========================
function minSymbols(field){
var get_smile = smileys();
var text = field.value;
for(var i=0; i<get_smile.length; i++){
for(var j=0; j<(text.length); j++){
if(get_smile[i]==text[j]){
text = field.value.replace(get_smile[i],"");
}
}
}
if(text.length < 50){
document.getElementById("saveB").disabled=true;
} else {
document.getElementById("saveB").disabled=false;
}
}
How the script should be in order to let it work? Thank you!
I'd start by changing how I define the smilies:
var smilies = [
{text: "[:rolleyes:]", exp: /\[\:rolleyes\:\]/g},
{text: "[:D]", exp: /\[\:D\]/g},
{text: "[:blink:]", exp: /\[\:blink\:\]/g},
{text: "[:unsure:]", exp: /\[\:unsure\:\]/g},
{text: "[8)]", exp: /\[8\)\]/g},
{text: "[:-x]", exp: /\[\:-x\]/g}
];
(I didn't immediately see any reason this had to be a function, but you can make it one if you want.) That's an array of objects, each object having a text property with the smiley text and an exp object with a RegExp that would match it (with the global flag set).
Then the function looks a bit like this:
function getLengthMinusSmilies(field) {
var text, index, length, smiley;
text = field.value;
length = text.length;
for (index = 0; index < smilies.length; ++index) {
smiley = smilies[index];
while (smiley.exp.test(text)) {
length -= smiley.text.length;
}
}
return length;
}
That avoids creating and throwing away temporary strings. It just counts matches of smilies and disregards their length.
You don't have to use objects with text and exp values, you can use paralle arrays if you like:
var smilies = [
"[:rolleyes:]",
"[:D]",
"[:blink:]",
"[:unsure:]",
"[8)]",
"[:-x]"
];
var matchExps = [
/\[\:rolleyes\:\]/g,
/\[\:D\]/g,
/\[\:blink\:\]/g,
/\[\:unsure\:\]/g,
/\[8\)\]/g,
/\[\:-x\]/g
];
...and then adjust the loop in the function accordingly. Using one array with objects tends to be more maintainable, but if you need an array elsewhere...
function minSymbols(field){
var get_smile = smileys();
var text = field.value;
for(var i=0; i<get_smile.length; i++){
text = text.replace(get_smile[i],"");
}
}
function getTxtLen()
{
var str=document.getElementById('myTxtBox').value;
str=str.replace(/\[:some:\]/g,'');
str=str.replace(/\[:some2:\]/g,'');
alert(str.length);
}