I really need your help with this since this goes well beyond my level of capability of javascript coding.
I'd like to design a function that would accomplish one of the following two scenarios:
If there is no dash and number at the end of the string var 'fileno', then rewrite the string fileno and add the dash and then the count at the end.
var fileno = 'test'
var c = 4
fileno = 'test-4'
If there is already a dash and then a number at the end of the string, replace the dash-number with the new info below:
var fileno = 'test-2'
var c = 3
fileno = 'test-3'
You may use regular expression with String.prototype.replace():
fileno = fileno.replace(/-\d+$|$/, '-' + c);
It literally means: replace -{number} or nothing at the end of the string with -{c}.
var c = 3;
console.log( 'test'.replace(/-\d+$|$/, '-' + c) );
console.log( 'test-4'.replace(/-\d+$|$/, '-' + c) );
if(fileno[fileno.length - 2] === "-"){
fileno = fileno.substr(0,-1) + c;
} else {
fileno += "-" + c;
}
Just either append a new number if there is already a - in the second last position or append a new one.
Related
Supposing I have this:
var date = '2017-06-02';
How can I get:
var date = '2017,5,2';
So, I need to :
replace the - by ,
remove the leading zero if applied for the first and second parameter.
remove 1 for the second value
Thanks so much.
Non-ninjutsu solution:
var date = '2017-06-02';
var y = date.split("-")[0];
var m = date.split("-")[1];
var d = date.split("-")[2];
var final = y + "," + (parseInt(m)-1) + "," + parseInt(d);
console.log(final);
Try this
var date = '2017-06-02'
function convertDate(date){
var ddmmyy = date.split('-');
var withRemovedZero = ddmmyy.map(function(x){return parseInt(x)});
withRemovedZero[1] = withRemovedZero[1] -1;
return withRemovedZero.join(",");
}
console.log(convertDate(date))
var date = '2017-06-22';
var parts = date.split("-"); // split by '-' to get an array of parts
parts[0] = +parts[0]; // convert to number to remove any leading 0's
parts[1]--; // increment or decrement the part you need
parts[2] = +parts[2]; // convert to number to remove any leading 0's
var newDate = parts.join(","); // join the parts together using ','
console.log(newDate);
parts[1]-- is the same as parts[1] = parts[1] - 1 (parts[1] is the second part i.e. '06'). The parts ar strings, but whe using an operator that only applies on numbers such as -, then the part get converted to a number. If you use the + operator, however, this will cause a problem, as + wil be regarded as string concatination and not as numerical addition. A safter appraoch is to convert the string to a number first (either implicitly using unary + operator, or explicitly using parseInt or Number):
parts[1] = parseInt(parts[1]) - or + theNumberYouWant;
You can do a regular expression based string replacement. The following uses capturing groups to get the year, month and day, then uses a function to produce the replacement text.
var date = '2017-06-02';
var output = date.replace(/(\d+)-(\d+)-(\d+)/, function(_, y, m, d) {
return y + ',' + (m - 1) + ',' + +d;
});
console.log(output);
The result of the subtraction on the month is a number not a string, so it drops any leading zero automatically, then for the day I've used the unary plus operator to convert it to a number to drop its leading zero (if present), and both are concatenated into a string with the required commas.
Using split you can do that.
var date = '2017-06-02';
var date_array = date.split("-");
var first = date_array[1].charAt(0);
if(first=='0'){
first = date_array[1].substr(1);
}
else{
first = date_array[1];
}
var second = date_array[2].charAt(0);
if(second=='0'){
second = date_array[2].substr(1);
}
else{
second = date_array[2];
}
var output = date_array[0]+","+first+","+second;
document.write(output);
Output,
2017,6,2 // If date is 2017-06-02
2017,12,24 // If date is 2017-12-24
I am making a calculator in JavaScript and I want to know how to turn a string into an expression.
var numbers = "5+5+6";
numbers = +numbers;
document.querySelector('.screen').innerHTML = numbers;
Adding + before the variable does not seem to work. I would appreciate it if someone helped.
You can use the eval() function like this:
var numbers = "5+5+6";
document.querySelector('.screen').innerHTML = eval(numbers);;
Evaluate/Execute JavaScript code/expressions:
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
The result of res will be:
200
4
27
Without using eval, which is cheating - you could always write a simple calculator app.
First, take advantage of String.split() as follows
var numbers = "5+5+6";
numbers.split("");
// => ["5","+","5","+","6"]
Now all you need to do is figure out how to evaluate it while keeping the order of operations correct. Hint: it might involve trees.
Try using String.prototype.match() , Array.prototype.reduce() , Number() . See also Chrome App: Doing maths from a string
var numbers = "5+5+6";
var number = numbers.match(/\d+|\+\d+|\-\d+/g)
.reduce(function(a, b) {
return Number(a) + Number(b)
});
document.querySelector(".screen").innerHTML = number;
<div class="screen"></div>
Assume that there is a string like this:
var content = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20";
I want to add <br /> after every 5 dots.
So, the result should be:
1.2.3.4.5.<br />
6.7.8.9.10.<br />
11.12.13.14.15.<br />
16.17.18.19.20.<br />
I want to do this without a for loop. Is it possible with just regex?
i'm doing this with this code;
regenerate:function(content,call){
var data2;
var brbr = content.replace(/[\u0250-\ue007]/g, '').match(/(\r\n)/g);
if (brbr !== "") {
data2 = content.replace(/[\u0250-\ue007]/g, '').replace(/(\r\n)/gm, "<br><br>");
} else {
data2 = content.replace(/[\u0250-\ue007]/g, '');
}
var dataArr = data2.split(".");
for (var y = 10; y < dataArr.length - 10; y += 10) {
var dataArrSpecific1 = dataArr[y] + ".";
var dataArrSpecific2 = dataArr[y] + ".<br>";
var dataArrSpecificBosluk = dataArr[y + 1];
var data3 = data2.replace(new RegExp(dataArrSpecific1.replace(/[\u0250-\ue007]/g, ''), "g"), "" + dataArrSpecific2.replace(/[\u0250-\ue007]/g, '') + "");
data3 = data3.replace(new RegExp(dataArrSpecificBosluk.replace(/[\u0250-\ue007]/g, ''), "g"), " " + dataArrSpecificBosluk.replace(/[\u0250-\ue007]/g, '') + "");
data2 = data3;
}
call(data2.replace(/[\u0250-\ue007]/g, ''));
}
Actually , i want to refactoring this code
Working bin:http://jsbin.com/dikifipelo/1/
var string = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20." ;
string = string.replace(/(([^\.]+\.){5})/g, "$1<br/>");
Works with any type and length of characters between the dots.
Explanation:
The pattern /(([^.]+.){5})/g can be broken down as such:
[^\.] - any character that is not a dot
[^\.]+ - any character that is not a dot, one or more times
[^\.]+\. - any character that is not a dot, one or more times, followed by a dot
([^\.]+\.){5} - any character....dot, appearing five times
(([^\.]+\.){5}) - any...five times, capture this (all round brackets capture unless told not to, with a ?: as the first thing inside them)
the /g/ flag makes it so that the whole string is matched - ie, all matches are found
"$1" represents the results of the first group (or bracket)
so, the replace function finds all instances of the pattern in the string, and replaces them with the match itself + a line break (br).
Once you learn regular expressions, life is never the same.
I am trying to create a cross browser animationListener, and have an issue with the substr function!
function animationEventListener(elem, listener, callback){
if(!elem){return;}
if(listener.length < 0){ console.error("Add event type listener"); }
listener = listener.toLowerCase();
var _prefix = ["", "o", "webkit", "MS"];
var _anmkeyword = new String("animation");
var _keywordlength = _anmkeyword.length;
var _nlistener;
for(var i = 0; i < 4; i++){
if(_prefix[i] == "MS" || _prefix[i] == "webkit"){
var _ol = _keywordlength + 1;
_nlistener = listener.substr(0, 1).toUpperCase()
+ listener.substr(1, listener.length - (listener.length - _keywordlength)-1)
+ listener.substr(9, 10).toUpperCase()
+ listener.substr(_keywordlength+1, listener.length);
}
console.log(_prefix[i] + listener + "\n" + _nlistener);
}
}
try it you see:
listener = "animationend";
listener.substr(9, 10); // returns "end";
WHY?
The second parameter to the substr function is how many characters to extract (length). The first parameter sets where to start from. You can read more here in the documentation.
So your line of code : listener.substr( 9, 10 ); basically says "give me 10 characters from the 9th index". However, since there simply isn't 10 characters after the 9th index, the command will return everything that it can which is the rest of the string.
To extract only one character after the 9th index all you'll have to do is use this command:
listener.substr( 9, 1 );
Alternatively, if you want to extract a string between two indexes, you can use the substring() function:
listener.substring( 9, 10 );
The difference between substr and substring is:
text.substr(a, b); //a=index to start, b=amount of letters to capture
text.substring(a, b); //a=index to start, b=index to stop
So in your case you can use:
listener.substr(9, 1);
or
listener.substring(9, 10);
How can i prevent to javascript interpret my numeric vars from string vars?
var a = 100;
var b = -10
var c = a + b // 10-10 (string)
lets say i allways want
var c = a + b = 100+(-10) = 90 (number)
In your example c will always be 90, however;
var a = 100;
var b = "-10";
var c = a + b // "100-10" (string)
to prevent this convert the string to an integer;
var c = a + parseInt(b, 10);
or with a unary+
var c = a + +b;
Your code example...
var a = 100;
var b = -10
var c = a + b // 90 (number)
...won't do that unless one of the operands is a String. In your example, both are Number.
If you do have numbers inside of Strings, you can use parseInt() (don't forget to pass the radix of 10 if working in decimal) or possibly just prefix the String with + to coerce it to Number.
Your code works fine. See here.
JavaScript will always do the latter, as long as both of the variables you are adding are numbers.
The most concise way is prepending a + if you aren't certain whether the variables are numbers or strings:
var a = "100";
var b = "-10";
var c = +a + +b; // 90
This works since +"123" === 123 etc.