Maintaining string length by adding zeros - javascript

I need to pass a string with at least has a length of 10. How do I add 0's to fill the remaining blank spaces so it will always have a length of 10?
This is what I tried but does not work as expected.
var passString = "Abcdefg";
if (passString.length<10){
var len = passString.length;
var missing = 10-len;
passString = passString + Array(missing).join("0")
}

Concat zeros to the end of the string and use slice or substring or substr.
var passString = "ABC";
var fixed = (passString + "0000000000").slice(0,10);
console.log(fixed);
Based on comment, I skipped the if, but you can just do a basic if
var passString = "ABC";
var fixed = passString;
if (passString.length<10) {
fixed = (passString + "0000000000").slice(0,10);
}
console.log(fixed);
or ternary operator
var passString = "ABC";
var fixed = passString >=10? passString : (passString + "0000000000").slice(0,10);
console.log(fixed);
or just override the original with an if
var passString = "ABC";
if (passString.length<10) {
passString = (passString + "0000000000").slice(0,10);
}
console.log(passString);

please try below code
var passString = "Abcdefg";
if (passString.length<10){
var len = passString.length;
var missing = 10-len;
passString =passString+ new Array(missing + 1).join("0");
}
thanks

You can do it in one line (I love giving one liners)
passString = (passString + Array(11).join('0')).substr(0,Math.max(10,passString.length))

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));

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

Random character in RegEx replace

I want to replace G$0 in the string gantt(G$0,$A4,$B4) with gantt(<>G$0<>,$A4,$B4). So I have the following code:
var str = '=gantt(G$0,$A4,$B4) ';
var val = "G$0";
var val2 = val.replace(/\$/, "\\$")
var reg = new RegExp(val2, 'g');
var str = str.replace(reg, '<>' + val + '<>');
The result in IE is: =gantt(<>GG$0<>,$A4,$B4)  (note the GG). The problem seems to be IE10 specific.
Why is this happening, is this an IE bug?
The replace should assume a string could contain multiple instances of **G$0**.
There's no need to use RegEx at all. Stick to regular string replacement, and you won't have to escape the val string.
var str = '=gantt(G$0,$A4,$B4) ';
var val = "G$0";
var result = str.replace(val, '<>' + val + '<>');
If you want to replace multiple instances of val this can be done with .split and .join:
var str = '=gantt(G$0,$A4,$B4,G$0) ';
var val = "G$0";
var result = str.split(val).join('<>' + val + '<>');

How to write regular expression in the following case using javascript?

var value = "ID=advIcon1&CLASS=advIcon&PAGE=43&TOP=2%&LEFT=15%&WIDTH=20%&HEIGHT=10%&RSC=http://www.canon.com.hk/40th/index.html?source=seriesbanner&ICON=http://203.80.1.28/FlippingBook/Dev/Frontend/source/adv/tc_bn_314.jpg&ALT=Cannon Adv"
What I would like to achieve is from
&RSC=http://www.canon.com.hk/40th/index.html?source=seriesbanner
to
&RSC=http://www.canon.com.hk/40th/index.html?source#seriesbanner
which replace all the "=" between &RSC and &ICON
value = value.replace (/&RSC=%[=]+%&ICON/,/&RSC=%[#]+%&ICON/);
The above is the code I tried, not working though, how to fix the problem ? thanks
I would do it like this:
var value = "ID=advIcon1&CLASS=advIcon&PAGE=43&TO...";
var startIndex = value.indexOf("&RSC");
var endIndex = value.indexOf("&ICON");
var head = value.substring(0, startIndex);
var tail = value.substring(endIndex);
var body = value.substring(startIndex, endIndex);
var result = head + body.replace(/=/g, '#') + tail;
I don't see any advantage in trying to do the whole thing with one crazy regex.
That will only make your code harder to read and less efficient.
Better yet, make it a function you can re-use:
// Replaces every occurrence of replaceThis with withThis in input between
// startPattern and endPattern.
function replaceCharactersBetween(input, startPattern, endPattern, replaceThis, withThis) {
var startIndex = input.indexOf("startPattern");
var endIndex = input.indexOf("endPattern");
var head = input.substring(0, startIndex);
var tail = input.substring(endIndex);
var body = input.substring(startIndex, endIndex);
var regex = new RegExp(replaceThis, 'g');
return head + body.replace(regex, withThis) + tail;
}
Try:
value = value.replace(/RSC=([^=]+)=([^=]+)/, 'RSC=$1#$2');
You should look at endoceURIComponent() as well.

String to array then remove last element

I have the strings below and I am trying to remove the last directory from them but I cant seem to get the grasp of it.
JavaScript
var x = path.split("/")
alert(path +' = ' +x.slice(0, -1));
Expected Result
/foo/bar/ = /foo/
/bar/foo/ = /bar/
/bar/foo/moo/ = /bar/foo/
Try:
let path = "/bar/foo/moo/";
let split = path.split("/");
let splicedStr = split.slice(0, split.length - 2).join("/") + "/";
console.log(splicedStr);
Try:
var sourcePath="/abc/def/ghi";
var lastIndex=sourcePath.lastIndexOf("/");
var requiredPath=sourcePath.slice(0,lastIndex+1);
Output: /abc/def/

Categories

Resources