How to split a number after n digits in javascript? - javascript

I have a number 2802 which is stored as a string in the backend. I want to split this number into 2 parts as 28 and 02 which should be shown as date 28/02? How can I do it with '/' in between them?

Try this : you can use substring as shown below. substring used for getting string between start index and end index. In your case, get string from 0 to 1 and then 2 to 3.
var str = "2802";
str = str.substring(0,2) + "/" + str.substring(2,4);
alert(str);
More information on Substring

Solution with regex
var res = "2802".match(/\d{2}/g).join('/');
document.write(res);

Are you asking about simple string manipulation?
var str = "1234";
var res = str.substr(0, 2)+"/"+str.substr(2,4);

You can do this:
var str = "2802";
str = str.split('').map(function(el, i){
if(i == 2){ el = '/'+el}
return el;
});
document.querySelector('pre').innerHTML = str.join('');
<pre></pre>
With regular expression:
var str = "2802";
str = str.replace(/(.{1,2}$)/gi, '/$1');
document.querySelector('pre').innerHTML = str;
<pre></pre>

var str = "2802";
var output = [str.slice(0, 2), str.slice(2)].join('/');

In this context conside 2802, 28 is date and 02 is month
Here 112, 028 what is date and month ?

A more generic solution could be
var num = 2802;
var output = String(num).match(new RegExp('.{1,2}', 'g')).join("/");
replace 2 with which ever number to split the number after n digits.
var n = 2;
var output = String(num).match(new RegExp('.{1,'+n+'}', 'g'));

var db_date = '112';
var date_str = '';
if(db_date.slice(0,1)==0){
var date_val = db_date.slice(0,2);
var month_val = db_date.slice(2,3);
if(month_val<=9){
month_val = '0'+month_val;
}
}else{
var date_val = db_date.slice(0,1);
date_val = parseInt(date_val);
if(date_val<=9){
date_val = date_val.toString();
date_val = '0'+date_val;
}
var month_val = db_date.slice(1,3);
}
alert(date_val+'/'+month_val);

Related

How to increment a string in JavaScript containing leading zeros?

I have string like:
MPG_0023
I want to find something like
MPG_0023 + 1
and I should get
MPG_0024
How to do that in JavaScript? It should take care that if there are no leading zeros, or one leading zero should still work like MPG23 should give MPG24 or MPG023 should give MPG024.
There should be no assumption that there is underscore or leading zeros, the only thing is that first part be any string or even no string and the number part may or may not have leading zeros and it is any kind of number so it should work for 0023 ( return 0024) or for gp031 ( return gp032) etc.
Here's a quick way without using regex.. as long as there's always a single underscore preceding the number and as long as the number is 4 digits, this will work.
var n = 'MPG_0023';
var a = n.split('_');
var r = a[0]+'_'+(("0000"+(++a[1])).substr(-4));
console.log(r);
Or if you do wanna do regex, the underscore won't matter.
var n = "MPG_0099";
var r = n.replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4));
console.log(r);
You can use the regular expressions to make the changes as shown in the following code
var text = "MPG_0023";
var getPart = text.replace ( /[^\d.]/g, '' ); // returns 0023
var num = parseInt(getPart); // returns 23
var newVal = num+1; // returns 24
var reg = new RegExp(num); // create dynamic regexp
var newstring = text.replace ( reg, newVal ); // returns MPG_0024
console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
Using regex along with the function padStart
function add(str, n) {
return str.replace(/(\d+)/, function(match) {
var length = match.length;
var newValue = Number(match) + n;
return newValue.toString(10).padStart(length, "0");
});
}
console.log(add("MPG_023", 101));
console.log(add("MPG_0023", 101));
console.log(add("MPG_0000023", 10001));
console.log(add("MPG_0100023", 10001));
Using regular expression you can do it like this.
var text1 = 'MPG_0023';
var text2 = 'MPG_23';
var regex = /(.*_[0]*)(\d*)/;
var match1 = regex.exec(text1);
var match2 = regex.exec(text2);
var newText1 = match1[1] + (Number(match1[2]) + 1);
var newText2 = match2[1] + (Number(match2[2]) + 1);
console.log(newText1);
console.log(newText2);
Increment and pad the same value (comments inline)
var prefix = "MPG_"
var padDigit = 4; //number of total characters after prefix
var value = "MPG_0023";
console.log("currentValue ", value);
//method for padding
var fnPad = (str, padDigit) => (Array(padDigit + 1).join("0") + str).slice(-padDigit);
//method to get next value
var fnGetNextCounterValue = (value) => {
var num = value.substring(prefix.length); //extract num value
++num; //increment value
return prefix + fnPad(num, padDigit); //prepend prefix after padding
};
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
One way would e to split the string on the "_" character, increment the number and then add the zeros back to the number.
var testString = "MGP_0023";
var ary = testString.split("_");
var newNumber = Number(ary[1]) + 1;
var result = ary[0] + pad(newNumber);
// helper function to add zeros in front of the number
function pad(number) {
var str = number.toString();
while (str.length < 4) {
str = '0' + str;
}
return str;
}
You could cast to number, increment the value and cast back. Then check if you need leading zeros by looking at the length of the string.
Snippet below:
let str = "MPG_0023",
num = Number(str.substr(4)) + 1,
newStr = String(num);
function addLeading0(str) {
return str.length === 2 ? '00' + str : (str.length === 3 ? '0' + str : str);
}
console.log("MPG_" + addLeading0(newStr));

How to split two dimensional array in JavaScript?

I have string like below:
"test[2][1]"
"test[2][2]"
etc
Now, I want to split this string to like this:
split[0] = "test"
split[1] = 2
split[2] = 1
split[0] = "test"
split[1] = 2
split[2] = 2
I tried split in javascript but no success.How can it be possible?
CODE:
string.split('][');
Thanks.
Try this:
.replace(/]/g, '') gets rid of the right square bracket.
.split('[') splits the remaining "test[2[1" into its components.
var str1 = "test[2][1]";
var str2 = "test[2][2]";
var split = str1.replace(/]/g, '').split('[');
var split2 = str2.replace(/]/g, '').split('[');
alert(split);
alert(split2);
you can try :
string.split(/\]?\[|\]\[?/)
function splitter (string) {
var arr = string.split('['),
result = [];
arr.forEach(function (item) {
item = item.replace(/]$/, '');
result.push(item);
})
return result;
}
console.log(splitter("test[2][1]"));
As long as this format is used you can do
var text = "test[1][2]";
var split = text.match(/\w+/g);
But you will run into problems if the three parts contain something else than letters and numbers.
You can split with the [ character and then remove last character from all the elements except the first.
var str = "test[2][2]";
var res = str.split("[");
for(var i=1, len=res.length; i < len; i++) res[i]=res[i].slice(0,-1);
alert(res);

How to get substring value from main string?

I have string similar to this one.
HTML
var str = "samplestring=:customerid and samplestring1=:dept";
JS
var parts = str.split(':');
var answer = parts;
I want to trim substrings which starts with colon: symbol from the main string
But it is returing the value like this
samplestring=,customerid and samplestring1=,dept
But I want it something like this.
customerid,dept
I am getting main string dynamically it may have colon more then 2.
I have created a fiddle also link
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.match(/:(\w+)/g).map(function(s){return s.substr(1)}).join(","))
you can try regex:
var matches = str.match(/=:(\w+)/g);
var answer = [];
if(matches){
matches.forEach(function(s){
answer.push(s.substr(2));
});
}
Here's a one-liner:
$.map(str.match(/:(\w+)/g), function(e, v) { return e.substr(1); }).join(",")
Try
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(':');
var dept = parts[2];
var cus_id = parts[1].split(' and ')[0];
alert(cus_id + ", " + dept );
Using this you will get o/p like :customerid,dept
this will give you what you need...
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(' and ');
var answer = [];
for (var i = 0; i < parts.length; i++) {
answer.push(parts[i].substring(parts[i].indexOf(':')+1));
}
alert(answer);
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.replace(/[^:]*:(\w+)/g, ",$1").substr(1))
You can try it like this
var str = "samplestring=:customerid and samplestring1=:dept and samplestring11=:dept";
var results = [];
var parts = str.split(' and ');
$.each(parts, function( key, value ) {
results.push(value.split(':')[1]);
});
Now the results array contains the three values customerid, dept, and dept
Here \S where S is capital is to get not space characters so it will get the word till first space match it, so it will match the word after : till the first space and we use /g to not only match the fisrt word and continue search in the string for other matches:
str.match(/:(\S*)/g).map(function(s){return s.substr(1)}).join(",")

JavaScript Split, Split string by last DOT "."

JavaScript Split,
str = '123.2345.34' ,
expected output 123.2345 and 34
Str = 123,23.34.23
expected output 123,23.34 and 23
Goal : JS function to Split a string based on dot(from last) in O(n).
There may be n number of ,.(commas or dots) in string.
In order to split a string matching only the last character like described you need to use regex "lookahead".
This simple example works for your case:
var array = '123.2345.34'.split(/\.(?=[^\.]+$)/);
console.log(array);
Example with destructuring assignment (Ecmascript 2015)
const input = 'jquery.somePlugin.v1.6.3.js';
const [pluginName, fileExtension] = input.split(/\.(?=[^\.]+$)/);
console.log(pluginName, fileExtension);
However using either slice or substring with lastIndexOf also works, and albeit less elegant it's much faster:
var input = 'jquery.somePlugin.v1.6.3.js';
var period = input.lastIndexOf('.');
var pluginName = input.substring(0, period);
var fileExtension = input.substring(period + 1);
console.log(pluginName, fileExtension);
var str = "filename.to.split.pdf"
var arr = str.split("."); // Split the string using dot as separator
var lastVal = arr.pop(); // Get last element
var firstVal = arr.join("."); // Re-join the remaining substrings, using dot as separator
console.log(firstVal + " and " + lastVal); //Printing result
I will try something like bellow
var splitByLastDot = function(text) {
var index = text.lastIndexOf('.');
return [text.slice(0, index), text.slice(index + 1)]
}
console.log(splitByLastDot('123.2345.34'))
console.log(splitByLastDot('123,23.34.23'))
I came up with this:
var str = '123,23.34.23';
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
document.getElementById('output').innerHTML = JSON.stringify(result);
<div id="output"></div>
let returnFileIndex = str =>
str.split('.').pop();
Try this:
var str = '123.2345.34',
arr = str.split('.'),
output = arr.pop();
str = arr.join('.');
var test = 'filename.....png';
var lastStr = test.lastIndexOf(".");
var str = test.substring(lastStr + 1);
console.log(str);
I'm typically using this code and this works fine for me.
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
console.log(afterDot);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Note: Replace quoted string to your own need
My own version:
var mySplit;
var str1;
var str2;
$(function(){
mySplit = function(myString){
var lastPoint = myString.lastIndexOf(".");
str1 = myString.substring(0, lastPoint);
str2 = myString.substring(lastPoint + 1);
}
mySplit('123,23.34.23');
console.log(str1);
console.log(str2);
});
Working fiddle: https://jsfiddle.net/robertrozas/no01uya0/
Str = '123,23.34.23';
var a = Str.substring(0, Str.lastIndexOf(".")) //123,23.34
var b = Str.substring(Str.lastIndexOf(".")) //23
Try this solution.
Simple Spilt logic
<script type="text/javascript">
var str = "123,23.34.23";
var str_array = str.split(".");
for (var i=0;i<str_array.length;i++)
{
if (i == (str_array.length-1))
{
alert(str_array[i]);
}
}
</script>
The simplest way is mentioned below, you will get pdf as the output:
var str = "http://somedomain.com/dir/sd/test.pdf";
var ext = str.split('.')[str.split('.').length-1];
Output: pdf

How to get a numeric value from a string in javascript?

Can anybody tell me how can i get a numeric value from a string containing integer value and characters?
For example,I want to get 45 from
var str="adsd45";
If your string is ugly like "adsdsd45" you can use regex.
var s = 'adsdsd45';
var result = s.match(/([0-9]+)/g);
['45'] // the result, or empty array if not found
You can use regular expression.
var regexp = /\d+/;
var str = "this is string and 989898";
alert (str.match(regexp));
Try this out,
var xText = "asdasd213123asd";
var xArray = xText.split("");
var xResult ="";
for(var i=0;i< xArray.length - 1; i++)
{
if(! isNan(xArray[i])) { xResult += xArray[i]; }
}
alert(+xResult);
var str = "4039";
var num = parseInt(str, 10);
//or:
var num2 = Number(str);
//or: (when string is empty or haven't any digits return 0 instead NaN)
var num3 = ~~str;
var strWithChars = "abc123def";
var num4 = Number(strWithChars.replace(/[^0-9]/,''));

Categories

Resources