I'm trying to get the length of the characters that I attain from innerHTML and it's kind of come down to last resort, but can't seem to find a more efficient way as the data is inside a slider that I'm trying to use to get the lower value and higher value.
var lvalue=document.getElementById("lval").innerHTML;
then I'm spiting the string in the spaces:
var larr=lvalue.split(" ");
The innerHTML value is something like this "2413dsk 134dfa134".
And when i use larr[0].length, I get 1 when I need 7. Is there a solution?
I think it would go something like this:
var lvalue = document.getElementById("lval").innerHTML;
var larr = lvalue.split(' ');
var len = 0;
// For each iterates over the index of arrays
for(var i in larr) {
len += larr[ i ].length // Acummulate the length of all the strings
}
Or alternatively you could count the spaces first and then substract it from the total length.
// Some people argue about extending the native objects
// but in this case I think this method is a natural fit.
String.prototype.count = function( character ) {
var l = 0;
// `this` refers to the string itself
for(var c in this) n = this[ c ] === character ? ++n : n;
return n;
}
An then use it like so:
var lvalue = document.getElementById("lval").innerHTML;
// Subtract total length minus the number of spaces
var len = lvalue.length - lvalue.count(' ');
This might be caused by a preceding or leading space.
Try trimming the extra spaces :
var lvalue=document.getElementById("lval").innerHTML.replace(/^\s+/gi,'').replace(/\s+$/gi,'');
var larr=lvalue.split(" ");
I didn't see any problem with your code. I run a test here: http://desdegdl.com/lval.html
Probably, you have one or more spaces at the begining of lval's inner HTML.
If there is someone like me that doesn't want to use JQuery, here is a example in javascript (only)...
The files
The html file...
<!-- start body -->
<body>
<!-- start section -->
<section id="bar"></section>
<!-- end section -->
</body>
<!-- end body -->
The javascript file...
/* start - wut element do ya wanna get? */
foo = document.getElementById('bar');
/* end - wut element do ya wanna get? */
/* start function */
function isEmpty(){
if (foo.innerHTML.length === 0) {
/* your code here */
}
}
/* end function */
What I did
In the HTML
Quite simple, I just created a section and assigned an ID on it. This ID will be used to call her in our javascript.
In the JavaScript
In the var fooI I called the section whose I gave an ID.
After it I created a function that "do something" if the length of a element is equal zero.
Considerations
It works, but if you have a space or a line break the code will not consider it as "empty"...
Related
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);
I am currently working on a project that will allow me to bring in a string that would have a designated token that I will grab, get the designated value and remove the token and push to an array. I have the following condition which I am using split in JavaScript but it is not splitting on the designated ending token.
This is the beginning string
"~~/Document Heading 1~~<div>This is a test <b>JUDO</b> TKD</div>~~end~~<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>"
Current Code Block
var segmentedStyles = [];
var contentToInsert = selectedContent.toString();
var indexValue = selectedContent.toString().search("~~");
if (indexValue <= 0) {
var insertionStyle = contentToInsert.split("~~");
segmentedStyles.push(insertionStyle);
}
The designated token is enclosed by a "~~ .... ~~". In this code Block it is going through the condition but the string it is not splitting correctly. I am currently getting the Following string pushed to my array.
This is my current result
[,/Document Heading 1<div>This is a test <b>JUDO</b> TKD</div>end,
<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>]
My Goal
I would like to split a string that is coming in if a token is present. For example I would like to split a string starting from ~~.....~~ through ~~end~~. The array should hold two values like the following
segmentedStyles = [<div>This is a test <b>JUDO</b> TKD</div>],[<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>]
You could use a regular expression for matching the parts.
var string = '~~/Document Heading 1~~<div>This is a test <b>JUDO</b> TKD</div>~~end~~<div class="/Document Heading 1">This is a test <b>JUDO</b> TKD</div>',
array = string.split('~~').filter(function (_, i) {
return i && !(i % 2); // just get element 2 and 4 or all other even indices
});
console.log(array);
Assuming the string always starts with ~~/ you could use the following regex to get the array you want
~~([^\/].*)~~end~~(.*)
https://regex101.com/r/hJ0vM4/1
I honestly didn't quite understand what you're trying to accomplish haha, but I sort of understood what you're trying to do :)
First, just trying to make it clear some stuff. If you split() your string using /~~/ as the Regular Expression for splitting you'll get all the bits surrounded by "~~" in an array, like you did.
Second, if you change the tokens to ~~START~~ and ~~END~~ (tokens that never change) you can accomplish what you want by simply doing string.split(/~~(START|END)~~/) - Much shorter and quicker ;)
Third is the string always in the format ~~<something>~~THE STUFF YOU WANT~~end~~MORE STUFF YOU WANT? If it is, I'd suggest doing this:
function splitTheTokens(str) {
var result = [];
var parts = str.split(/~~end~~/);
for (var i = 0; i < parts.length; i++) {
if (!parts[i]) { continue; } // Skips blanks
if (parts[i].indexOf("~~") == 0) {
// In case you want to do something with the name thing:
var thisPartName = parts[i].substring(2, parts[i].indexOf("~~", 2));
// What (I think) you actually want
var thisPartValue = parts[i].substring(thisPartName.length + 4);
result.push(thisPartValue);
}
else {
result.push(parts[i]);
}
}
return result;
}
Hope this helps :D
Sorry for the odd title, I'm sure someone has asked something similar before. My question is, I'm building a string with html tags enclosed, my question is is it better to test and add extra tags, in this case a <br />, or to add the tag anyway and have a 'remove' line at the end, which is faster?:
So at the moment we have
bFirst = true;
label = '';
if(...)
{
if (!bFirst)
label += '<br/>';
label+= 'some more text'
}
if(...)
{
if (!bFirst)
label += '<br/>';
label+= 'some more text'
}
and so on...
or
if()
{
label+= 'some more text <br />'
}
and then just remove the last <br /> using the string.substring() method.
Which is faster, better, more correct? I don't need code it is really a performance question, I could test it but I'm sure someone has done this before.
Thanks.
You can define which way is the fastest with this procedure :
Requirements :
You will need an addon like firebug or pagespeed
You'll have to execute those two pages :
Add all extra text and then trim some :
<div id ="concat"></div>
<script type="text/javascript">
var someText = ""
// adds "foo" 10k times
for (i = 0; i < 10000; i++) {
someText += "foo"
}
// crops the 3 last characters off the string 5k times
for (i = 0; i < 5000; i++) {
someText.substr(someText.length - 3, someText.length);
}
// append the final string
$('#concat').append(someText);
</script>
On my browser, it takes between 0.19 sec and 0.30 sec.
Add extra text when it is needed
<div id ="if"></div>
<script type="text/javascript">
var someText = ""
var append = true;
for (i = 0; i < 15000; i++) {
//adds "foo" the first 10k times
if(append == true){
someText += "foo";
}
if(i == 10000){
append = false;
}
}
$('#if').append(someText);
</script>
This code iterates 15k times and only adds "foo" the first 10k times.
The execution of such code can take between 0.10 and 0.12 sec
Conclusion
Adding content to your string only when it is needed seems a better option in terms of performance.
Also, in terms of code readabilty, the second option should be used.
Quick and simple analysis:
First option makes a comparison and a memory reallocation.
Second option (supposing you'd be doing label = label.substring(...)) counts characters, if you want the first N characters, String.prototype.substring() will probably count N times while reading N bytes of characters. Finally, you allocate/reallocate memory.
Now which strategy appears more efficient?
If you're still in doubt try both methods under a timer.
I got 2 questions:
My function looks like that
function count() {
var value = ids.val();
return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(/\r\n|\r|\n/).length;
}
What I wanna do is, to skip whitespaces and count all new lines
For ex:
85
96
75
<whitespace>
76
count() must return 4 not 5. How can I modify my function?
How to convert line break seperated words/numbers to comma seperated content?
For ex:
85
96
75<whitespace>
<whitespace>
76
I want to trim all whitespaces and convert whole content into something like that 85,96,75,76. How can I do it ?
The easiest way would be .filter($.trim).map($.trim), which first removes any whitespace entries, and then cleans the remaining entries by removing surrounding spaces: http://jsfiddle.net/BtLzf/1/.
var vals = ids.val()
.split(/\r\n|\r|\n/)
.filter($.trim)
.map($.trim);
vals.length; // 4
vals.join(); // 85,96,75,76
.filter/.map are ES5 which means you'll need a shim for older browsers.
I think that you will need to do a loop for checking the length of each line, because in this case you're getting the number of end-of-line characters, which is 5 even if the line is empty... Getting this iterator you can also get the comma-list
I'd suggest using a regex pattern that cleans things up a bit better.
Perhaps:
^(\d+)\s?$
$(function(){
var matches = $('#txtInput').text().match(/^(\d+)\s?$/mg);
$('#txtResult').text(matches.join(','));
});
Working Example:
http://jsfiddle.net/mZ97L/
What about something like this?
// Count of items in the list.
function count(){
var list = delimitedList();
return list.split(",").length;
}
// Get list separated by comma.
function delimitedList(){
var value = ids.val();
return value.replace(/\s+/g, ",");
}
http://jsfiddle.net/wT23h/2/
I can not find the solution. I've tried to assume that count of \n symbols is the same with lines count, but sometimes this method works incorrectly (e.g. after paste text from clipboard)
i've tried different jQuery plugins, but still unsuccessfully.
any idea?
Why not just do this:
Take the text content only up to selectionStart then make it an array by splitting at eol
p = $('#Form_config').val().substr(0, $('#Form_config')[0].selectionStart).split("\n");
// line is the number of lines
line = p.length;
// col is the length of the last line
col = p[p.length-1].length;
Try to use this:
var pos = getCaretPos(document.formName.textareaName);
function getCaretPos(obj)
{
obj.focus();
if(obj.selectionStart) return obj.selectionStart;//Gecko
else if (document.selection)//IE
{
var sel = document.selection.createRange();
var clone = sel.duplicate();
sel.collapse(true);
clone.moveToElementText(obj);
clone.setEndPoint('EndToEnd', sel);
return clone.text.length;
}
return 0;
}
The descision is not so simple and requieres large amount of javascript code. So, finally i've used CodeMirror Project by Marijn Haverbeke (https://github.com/marijnh/CodeMirror)