split() loop: if string number = x, insert <br> - javascript

This question refers to one of mine about split(), and include an answered question about inserting specific thing if string number is x.
Basically, I have one big string, with a specific separator which is :, and I'm using .split() in a loop to print each part of the string into a different input using the separator to cut it. This works perfectly.
Now, what I want is to do a breakline after each 17 inputs (input 17 then linebreak, input 34 then linebreak, input 51...). I found a way to do it in the second link I shared, and the breakline works. The problem is that only the last line of inputs is now filled with the string parts (the last 7 parts of the string). All the other input are simply blank.
Here's the final code:
function cutTheString()
{
var str = document.getElementById('textareaString').value;
var arrayOfStrings = str.split(':');
for(var i = 0; i < arrayOfStrings.length; i++)
{
if ((i % 17) == 0)
{
document.getElementById('result').innerHTML += '<br />';
}
var div = document.getElementById('result');
var mi = document.createElement('input');
mi.setAttribute('type', 'text');
mi.setAttribute('size', '4');
mi.setAttribute('id', 'string' + (i+1));
div.appendChild(mi);
document.getElementById('string' + (i+1)).value = arrayOfStrings[i];
}
}
Interestingly, in if ((i % 17) == 0), let's replace 0 by x. If x < 17, only x - 17 inputs will be filled, starting by the last one of the list. If x > 17, all inputs will be filled, but the breaklines will obviously not work.
There is no error in the console, and my knowledge of Javascript makes me fail to understand why it's doing this. I quite see the correlation, but I can't think of any solution. I tried different operators than == without success.
You can test it on this JSFiddle. Thanks for your help!

Use
mi.setAttribute('value', arrayOfStrings[i]);
instead of
document.getElementById('string' + (i+1)).value = arrayOfStrings[i];
(before of div.appendChild(mi)).

Related

Search for string between two characters if next to a specific string

I am in need of some modification to my function to allow for a search of two strings on one line of a value. I am trying to work through this on my own but I need some help. Here is an example of a cell value being looked at. Assume there are no leading or trailing newlines. Also, all the cells have the same format. same number of lines, same structure of membertype: last, first etc.
Say I want to see if this cell contains a team lead with the name of last2 or a Manager with the name first4. Both the type of employee and name would be user inputted.
I tried using the following that I created with the help of this.
indexOf(':(.*):')
It returns the position of the content between and including the colons. Then I tried the following:
flatUniqArr[0].search('Supervisor:')
This is where I'm stuck. It returns the index to the last digit of the first line.
My thought was to do a search of the user inputted name between the colons if they follow the user inputted member type. How can I accomplish this?
Clarifications:
The end goal is to verify that the name and member type are on the same line and excluded from an array I am building for .setHiddenValues(). So if they are on the same line exclude from list.
Here is the function I will be adding it to:
var flatUniqArr = colValueArr.map(function(e){return e[0].toString();})
.filter(function(e,i,a){
return (a.indexOf(e) == i && !(visibleValueArr.some(function(f){
return e.search(new RegExp(f,'i')) + 1;
})));
});
return flatUniqArr;
Where flatUniqArr is the list of hidden values. colValueArr is the array of values from a column. visibleValueArr is the name which is user inputted and memberType will be the member type.
Attempts using Liora's solution: (Updated... Works now)
var flatUniqArr = []
var lines = []
Logger.log(visibleValueArr)
Logger.log(memberType)
for (var i = 0; i < colValueArr.length; i++){
lines = colValueArr[i].toString().split('\n');
var found = false;
for(var j = 0; j < lines.length; j++){
var data = lines[j].toLowerCase().split(':')
if(data[0] == memberType.toString().toLowerCase() && data[1].indexOf(visibleValueArr.toString().toLowerCase()) != -1){
found = true;
}
}
Logger.log(found)
if(found == false){flatUniqArr.push(colValueArr[i])}
}
return flatUniqArr;
It works now. It seems like a lot of code though. I'd be open to alternative solutions if they are faster and/or less lines of code.
Updated: Added .toString().toLowerCase() as the user may input lowercase values.
I assume all the line have this format.
If you split each line with the separator ":"
var array = value.split(":")
Then you'd have
array[0] //the current role
array[1] //the list of name
array[2] //the email
And you can check each names then
if(array[0] == "Team Lead" && array[1].indexOf("last2") != -1)
An example with a linesplit:
var lines = value.toString().split("\n");
var found = false;
for(var i = 0; i < lines.length ; i++){
var data = value.split(":")
if(data[0] == "Team Lead" && data[1].indexOf("last2") != -1){
found = true;
}
}
How about just building the regex using the user input?
function search(line, employeeType, employeeName) {
var regexp = '/' + employeeType + ': ' + employeeName + '/'
return line.search(regexp)
}
Or better yet, if it always occurs at the beginning of the string, just use startsWith()

Adding space to fill array length

I am working with a javascript program that needs to be formatted a certain way. Basically, I need to have each section of information from an array be a set length, for example 12 characters long, and no more than that.
The problem I am running into comes when a value in the array is NOT 12 characters long. If I have a value that is less than the 12 characters the remaining character allotment needs to be filled with blank spaces.
The length of each section of information varies in size and is not always 12. How can I add X number of blank spaces, should the length not meet the maximum requirement, for each section?
This is where I am at with adding space:
str = str + new Array(str.length).join(' ');
I am pretty sure what I have above is wrong but I believe I am on the right track with the .join function. Any ideas?
EDIT: I was asked to show a wanted outcome. It is a bit complicated because this javascript is being run out of a web report tool and not out of something like Visual Studio so its not traditional JS.
The outcome expected should look something like:
Sample Image
So as shown above the data is in one line, cutting off longer strings of information or filling in blank spaces if its too short for the "column" to keep that nice even look.
try this code and leverage the wonders of the map function:
let say your array is:
var myArr = ["123456789012", "12345678901", "123"];
now just apply this function
myArr.map(function(item){ //evalueate each item inside the array
var strLength = item.length; //apply this function to each item
if (strLength < 12){
return item + ' '.repeat(12-item.length) //add the extra spaces as needed
} else {
return item; // return the item because it's length is 12 or +
}
})
What you are looking for is the ' '.repeat(x) - where x is the times you want to repeat the string you have set, it could be '*'.repeat(2) and you would get '**', if you want to understand more about it look at the docs
depending on which version of javascript, this might work:
if (str.length < 12) str += ' '.repeat(12 - str.length);
Not exactly sure how you're setup -- but something like the following will accept an array and return another array with all its values being 12 characters in length.
var array = ['Test', 'Testing', 'Tested', 'This is not a Test'];
var adjustedArray = correctLength(array, 12);
function correctLength(array, length) {
array.map(function(v, i) {
if (array[i].length < length) {
array[i] += Array((length+1) - array[i].length).join('_');
}
// might not need this if values are already no greater than 12
array[i] = array[i].substring(0, length);
});
return array;
}
console.log(adjustedArray);

.replace method in JavaScript and duplicated characters

I'm trying to use JavaScript to insert HTML ruby characters on my text. The idea is to find the kanji and replace it with the ruby character that is stored on the fgana array. My code goes like this:
for (var i = 0; i < kanji.length; i++) {
phrase = phrase.replace(kanji[i],"<ruby><rb>" + kanji[i] + "</rb><rt>" + fgana[i] + "</rt></ruby>");
}
It does that just fine when there aren't duplicated characters to be replaced, but when there are the result is different from what I except. For example, if the arrays are like this:
kanji = ["毎朝","時","時"]
fgana = ["まいあさ"、"とき"、"じ"]
And the phrase is あの時毎朝6時におきていた the result becomes:
あの<ruby><rb><ruby><rb>時</rb><rt>じ</rt></ruby></rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 時 におきていた。
Instead of the desired:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt> におきていた。
To illustrate it better, look at the rendered example:
Look at how the first 時 receives both values とき and じ while the second receives nothing. The idea is to the first be とき and the second じ (as Japanese has different readings for the same character depending on some factors).
Whats might be the failure on my code?
Thanks in advance
It fails because the char you are looking for still exists in the replaced version:
...replace(kanji[i],"<ruby><rb>" + kanji[i]...
And this one should work:
var kanji = ["毎朝", "時", "時"],
fgana = ["まいあさ", "とき", "じ"],
phrase = "あの時毎朝 6 時におきていた",
rx = new RegExp("(" + kanji.join("|") + ")", "g");
console.log(phrase.replace(rx, function (m) {
var pos = kanji.indexOf(m),
k = kanji[pos],
f = fgana[pos];
delete kanji[pos];
delete fgana[pos];
return "<ruby><rb>" + k + "</rb><rt>" + f + "</rt></ruby>"
}));
Just copy and paste into console and you get:
あの<ruby><rb>時</rb><rt>とき</rt></ruby><ruby><rb>毎朝</rb><rt>まいあさ</rt></ruby> 6 <ruby><rb>時</rb><rt>じ</rt></ruby>におきていた
Above line is a bit different from your desired result thou, just not sure if you indeed want this:
...6 <ruby><rb>時</rb></ruby></rb><rt>じ</rt>...
^^^^^ here ^ not here?

JavaScript Syllable Counter - Counting Per Line

Current
I’ve re-worked this syllable counter script to:
Get the value of textarea 1.
Count the number of syllables in textarea 1.
Display the results in textarea 2.
Update the count every time the value of textarea 1 is edited.
Act as a function (be able to run in multiple instances if wanted).
Example function of current code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
11
Current code
Here is the existing code as a JSFiddle.
Goal
I would like this script to:
Count the syllables of textarea 1 on a per line basis: presumably by splitting the textarea 1 value where there are line breaks e.g. .split('\n');.
Output the results, showing the total number of syllables counted per line.
Example function of desired code
Input (Textarea 1)
i would appreciate
any help
at all
Results (Textarea 2)
6
3
2
Problem
I’m quite stuck as to how to do this and would really appreciate any help or JSFiddle showing how to work with the existing code to achieve this.
Notes
For anyone who may be interested using in the syllable count function code itself: it’s not 100% accurate and fails on some words but gives a good general idea.
Try this and let me know if it's what you needed.
Callouts:
I created an array that spits the lines up stores them var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);.
Then loop through that array and do exactly what you did before, but on each array entry. Then store the results in tempArr, and display the tempArr results.
See Fiddle
function $count_how_many_syllables($input) {
$("[name=set_" + $input + "]").keyup(function () {
var arrayOfLines = $("[name=set_" + $input + "]").val().match(/[^\r\n]+/g);
var tempArr = [];
var $content;
var word;
var $syllable_count;
var $result;
for(var i = 0; i < arrayOfLines.length; i++){
$content = arrayOfLines[i];
word = $content;
word = word.toLowerCase();
if (word.length <= 3) {
word = 1;
}
if (word.length === 0) {
return 0;
}
word = word.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/, '')
.replace(/^y/, '')
.match(/[aeiouy]{1,2}/g).length;
$syllable_count = word;
$result = $syllable_count;
tempArr.push($result);
}
$("[name=set_" + $input + "_syllable_count]").val(tempArr);
});
}
(function($) {
$count_how_many_syllables("a");
})(jQuery);

How do I get the unicode/hex representation of a symbol out of the HTML using JavaScript/jQuery?

Say I have an element like this...
<math xmlns="http://www.w3.org/1998/Math/MathML">
<mo class="symbol">α</mo>
</math>
Is there a way to get the unicode/hex value of alpha α, &#x03B1, using JavaScript/jQuery? Something like...
$('.symbol').text().unicode(); // I know unicode() doesn't exist
$('.symbol').text().hex(); // I know hex() doesn't exist
I need &#x03B1 instead of α and it seems like anytime I insert &#x03B1 into the DOM and try to retrieve it right away, it gets rendered and I can't get &#x03B1 back; I just get α.
Using mostly plain JavaScript, you should be able to do:
function entityForSymbolInContainer(selector) {
var code = $(selector).text().charCodeAt(0);
var codeHex = code.toString(16).toUpperCase();
while (codeHex.length < 4) {
codeHex = "0" + codeHex;
}
return "&#x" + codeHex + ";";
}
Here's an example: http://jsfiddle.net/btWur/
charCodeAt will get you the decimal value of the string:
"α".charCodeAt(0); //returns 945
0x03b1 === 945; //returns true
toString will then get the hex string
(945).toString(16); // returns "3b1"
(Confirmed to work in IE9 and Chrome)
If you would try to convert Unicode character out of BMP (basic multilingual plane) in ways above - you are up for a nasty surprise. Characters out of BMP are encoded as multiple UTF16 values for example:
"🔒".length = 2 (one part for shackle one part for lock base :) )
so "🔒".charCodeAt(0) will give you 55357 which is only 'half' of number while "🔒".charCodeAt(1) will give you 56594 which is the other half.
To get char codes for those values you might wanna use use following string extension function
String.prototype.charCodeUTF32 = function(){
return ((((this.charCodeAt(0)-0xD800)*0x400) + (this.charCodeAt(1)-0xDC00) + 0x10000));
};
you can also use it like this
"&#x"+("🔒".charCodeUTF32()).toString(16)+";"
to get html hex codes.
Hope this saves you some time.
for example in case you need to convert this hex code to unicode
e68891e4bda0e4bb96
pick two character time by time ,
if the dec ascii code is over 127 , add a % before
return url decode string
function hex2a(hex) {
var str = '';
for (var i = 0; i < hex.length; i += 2){
var dec = parseInt(hex.substr(i, 2), 16);
character = String.fromCharCode(dec);
if (dec > 127)
character = "%"+hex.substr(i,2);
str += character;
}
return decodeURI(str);
}

Categories

Resources