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).
Related
Edit
sorry if the question wasn't clear
here is the question..
create your version of javascript split function,
you may use indexOf and substring to help.
so if i give you a string "heellloolllloolllo" and i want to remove "llll" the function should return "heellloooolllo"
This what I did so far:
function split() {
var entered_string = document.forms["form1"]["str"].value;
var deleted_char = document.forms["form1"]["char"].value;
var index = entered_string.indexOf(deleted_char);
var i = deleted_char.length;
var result;
var x ;
for (x = 0; x< entered_string.length; x++ )
{
if (index < 0) {
result = entered_string;
} else {
result = entered_string.substring(0, index) +entered_string.substring(index+i);
}
}
alert(result)
}
Use the replace() function with the g at the end of your regular expression. It's called a "global modifier".
var string = 'heellloolllloolllo';
var res = string.replace(/llll/g, '');
console.log(res)
If your substring is a variable then you need to construct a new Regex object and set the g as the second parameter.
var string = 'heellloolllloolllo';
var find = 'llll';
var regex = new RegExp(find,'g');
var res = string.replace(regex, '');
console.log(res)
There are other useful modifiers you can use:
g - Global replace. Replace all instances of the matched string in the provided text.
i - Case insensitive replace. Replace all instances of the matched string, ignoring differences in case.
m - Multi-line replace. The regular expression should be tested for matches over multiple lines.
See this post for more information, credit to #codejoe.
Using String#replace and RegExp (the clean way)
var str = 'llllheellloolllloolllollll';
var matchStr = 'llll';
function removeSubString(str, matchStr) {
var re = new RegExp(matchStr, 'g');
return str.replace(re,"");
}
console.log(removeSubString(str, matchStr));
Using String#indexOf and String#substring
var str = 'llllheellloolllloolllollll';
var matchStr = 'llll';
function removeSubString(str, matchStr) {
var index = str.indexOf(matchStr);
while(index != -1) {
var firstSubStr = str.substring(0, index);
var lastSubStr = str.substring(index + matchStr.length);
str = firstSubStr + lastSubStr;
index = str.indexOf(matchStr);
}
return str;
}
console.log(removeSubString(str,matchStr))
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
I have a string like so:
var str = "FacebookExternalHit and some other gibberish";
Now I have a list of strings to test if they exist in str. Here they are in array format:
var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];
What is the fastest and/or shortest method to search str and see if any of the bots values are present? Regex is fine if that's the best method.
Using join you can do:
var m = str.match( new RegExp("\\b(" + bots.join('|') + ")\\b", "ig") );
//=> ["FacebookExternalHit"]
I don't know that regex is necessarily the way to go here. Check out Array.prototype.some()
var str = "FacebookExternalHit and some other gibberish";
var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];
var isBot = bots.some(function(botName) {
return str.indexOf(botName) !== -1;
});
console.log("isBot: %o", isBot);
A regular for loop is even faster:
var str = "FacebookExternalHit and some other gibberish";
var bots = ["FacebookExternalHit", "LinkedInBot", "TwitterBot", "Baiduspider"];
var isBot = false;
for (var i = 0, ln = bots.length; i < ln; i++) {
if (str.indexOf(bots[i]) !== -1) {
isBot = true;
break;
}
}
console.log("isBot: %o", isBot);
I must have a syntax error in my code but I can't see it. fiddle here
var comma = ',,';
var stop = '.。';
var expression = '/[]+/';
expression = expression.substr(0,2) + comma + stop + expression.substr(2);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
}
I'm expecting res.length to be 3 but it is always 1 and returns the full string. What am I missing?
/ is used as delimiter for RegExp literal. e.g. /[a-zA-Z]/g
/ is not needed when you pass a pattern to the RegExp constructor. e.g. new RegExp('[a-zA-Z]', 'g')
To resolve the problem, remove the / (and modify the rest of your code):
var expression = '[]+';
Or you can just pass a RegExp literal directly:
var res = "foo,吧。baz".split(/[,,.。]+/g);
When you creat your Regex you're using this: var expression = '/[]+/';. The / delimiters are for use when you're delaring a regex like this:
var expression = /[]+/; // note: no quotes.
You're using new Regexp(), so they're not required in your string. Removing them gives this:
var comma = ',,';
var stop = '.。';
var expression = '[]+';
expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
var item = document.createElement('li');
item.innerHTML = res[n];
document.getElementById('list').appendChild( item );
}
Which does what you expect. See this fiddle. I've adjusted the string indices and the loop index so that things work...
var expression = '/[]+/';
Should be
var expression = '[]+';
Also, adjust the substring indices accordingly
http://jsfiddle.net/2Pbm3/4/
Working like this :
var comma = ',,';
var stop = '.。';
var expression = '[]+';
expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');
var res = "foo,吧。baz".split(expression);
for ( var n=0; n < res.length; n++ ) {
var item = document.createElement('li');
item.innerHTML = res[n];
document.getElementById('list').appendChild( item );
}
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/