String to array then remove last element - javascript

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/

Related

Split String after third slash

Consider the following string "/path1/path2/file.png".
Is it possible to extract "/path1/path2 through an regex? If so can you provide an example and how it works for it? If not what would be the alternative?
I would do it this way:
var str = '/path1/path2/file.png';
var regex = /(?:\/.*\/)(.*)/;
var filename = regex.exec(str)[1];
console.log(filename);
JSFiddle: https://jsfiddle.net/Ldpoqf0n/1/
this is another way without using regex:
var parts = str.split('/');
console.log(parts[parts.length - 1]);
let str = '"/path1/path2/file.png"';
console.log(str.replace(/\/\w+.\w+"/, ''));
Try this
const src = '/path1/path2/file.png'
const getFirstPart = src => (src.match(/\/.*?\/.*?(?=\/)/) || [])[0]
console.log(getFirstPart(src))
With regexes:
var path = "/path1/path2/file.png";
var patt = new RegExp("\/.*?\/[^\/]*");
var subpath = patt.exec(path)[0];
console.log(subpath)
Without regexes:
function getSubpath(path, subpathLevel) {
var arr = path.split("/");
var subpath = "";
for(var i = 0; i < subpathLevel && i < arr.length; i++)
subpath += "/" + arr[i+1];
return subpath;
}
console.log(getSubpath("/path1/path2/file.png", 2));
In subpathLevel variable you can set the quantity of slashes you want to consider (in the example is 2).

How to get the ID from this URL?

I need a way to get the ID ( 153752044713801 in this case ) of this page:
https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801
I tried this code but doen't work:
var str = 0, pagefb = 0;
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var re1 = /^(.+)facebook\.com\/pages\/([-\w\.]+)\/([-\w\.]+)/;
if(re1.exec(fburl)){
str = re1.exec(fburl)[3];
pagefb = str.substr(str.lastIndexOf("-") + 1);
alert('ok');
}
try:
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split("/");
var myId = parts[parts.length-1];
alert(myId);
Try this regular expression: ^(.+)facebook\.com\/pages\/.*\/(\d*)
(in JavaScript, you have to add "/" at the beginning and end of the pattern like you did before)
this works for me
fburl.split('/')[fburl.split('/').length-1]
You can split the string using .split("/"). More information is availible on MDN
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713801';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
Basically it returns an array of the string split into multiple parts (at the character/s you put inside the brackets).
The parts[parts.length - 1] will get the last item in the array parts
Demo below (Don't worry about the document..., they just print out data):
var fburl = 'https://www.facebook.com/pages/%D8%A7%D9%84%D8%B4%D8%B1%D8%A7%D8%A8%D9%8A%D8%A9/153752044713‌​801/?ref=sfhsidufh';
var parts = fburl.split('/')
var myFacebookId = parts[parts.length - 1]
// If first digit is ?
if (myFacebookId[0] == '?') {
// Set myFacebookId to the second from last part
myFacebookId = parts[parts.length - 2]
}
document.write('MyFacebookId: ' + myFacebookId)

Maintaining string length by adding zeros

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

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 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.

Categories

Resources