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/
Related
Here's an example of the customer codes:
C000000123
C000000456
If I input C123 in the search box, "C000000123" will automatically display.
9 numbers are fixed.
Please help me, a short sample was shown to me but I don't get it.
function test(key, num, digit) {
let retStr;
xxxx (condition)
retun retStr;
}
here's an elaboration:
**
input:123
output:A00000123
input:1
output:A00000001
input:99999
output:A00099999
**
here's the detailed demand:
Since it takes time and effort to enter the management number “alphabet + numeric value 9 digits” on the search screen, when the alphabetic number and the number excluding the leading 0 are entered, it is automatically complemented so that it becomes 9 padded with zeros.
sorry i'm very very new to programming in javascript
Try this:
May be what you want...
Please test it and tell if its what you want.
function getOutput(input){
var str=input.substring(1,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output=input[0]+zrsub+""+str;
return output;
}
//Example: Call it like (NB any letter can be used):
getOutput("C123"); //or
getOutput("D123");
You can use .endsWith in js which takes a string and a search string and returns true if the specified string ends with the search string.
This function takes an array of customer ids and a search string and returns the matching customer id
function searchCustomer(customers, searchString) {
return customers.find(customer => customer.endsWith(searchString));
}
searchCustomer(['C000000123', 'C000000456'], 123); // "C000000123"
searchCustomer(['C000000123', 'C000000456'], 456); // "C000000456"
searchCustomer(['C000000123', 'C000000456', 'A00000001'], 1); //"A00000001"
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 have a Angular 2 / Typescript application string that contains number representations such as the following...
10000
10000.50
-10000
-10000.50
0
I want to add in commas after the thousand mark, for example...
10,000
10,000.50
-10,000
-10,000.50
0
What is the best way to do this?
I have tried some other answers but nothing is quite right.
For example this.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); and this.value.toLocaleString(); don't seem to handle both the comman and decimal point.
Have you tried
var some_string_value = '-10000.50';
parseFloat(some_string_value).toLocaleString()
?
Use "indexOf('.')",splice to two part,then use the method you found.
function addComma(num){
//some type check here
var numStr = num.toString();
var intEnd = numStr.indexOf('.');
var onePart =numStr,otherPart ='';
if(intEnd !== -1){
var onePart = numStr.slice(0,intEnd);
var otherPart = numStr.slice(intEnd);
}
return onePart.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')+otherPart;
}
You can use a pipe, you can find a full answer to your question here: Add Comma Separated Thousands to Number Inputs in Angular2
So im trying to write a function pattern which creates the following pattern upto n number of rows. If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
123456
23456
3456
456
56
6
I am trying to understand the solution of this question as below:
function pattern(n){
var output="";
for(i=1;i<n+1;i++){
for(j=i;j<n+1;j++){ //what is the purpose of this j loop?
output += j;
}
if(i!=n) output +="\n"; //I know \n can jump to next line, but what does this if statement mean? why I!=n?
}
return output;
}
// function definition
function pattern(n){
// declare a variable to collect the lines
var output="";
// there are n lines
for(i=1;i<n+1;i++){
// each line starts with the linenumber and ends with n
// so take a loop from i to n
for(j=i;j<n+1;j++){
// collect the numbers of each line as a string in the declared variable
output += j;
}
// if i!=n means: not the last line
if(i!=n) output +="\n";
}
// return the result of this function
return output;
}
UPDATE
But please let me point out, that the given solution is not very smart. Take a look at the following code:
Array.range = function(start, end) {
return Array.apply(null, Array(end+1)).map(function (_, i) {return i;}).slice(start);
}
function pattern(n){
var startValues = Array.range(1,n);
return startValues.map(function(i) { return Array.range(i,n); }).join('\n');
}
http://jsfiddle.net/afmchdwp/
First we define the static Method Array.range which helps us to define number ranges in javascript.
The pattern function can now use this ranges to create the numbers you need.
The first line of the function create a range from 1..n (the startnumbers of the lines).
The second line walks throu this array and transform every value 1..n into a range from the linenumber to n. With .join(), you can combine the characters of each line and combine the lines itself.
UPDATE 2
Here a updated fiddle without comma separated numbers (using join inside the closure): http://jsfiddle.net/afmchdwp/1/
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"...