This Javascript code removes the first file name from a file list and then removes its extension:
var fileNoExt = filelist.shift();
fileNoExt = fileNoExt.substr(0, fileNoExt.lastIndexOf('.'));
I'm curious - is it possible to turn this code into a one-liner?
How about using a regex?
If you want to enforce an extension after the ., use
var fileNoExt = filelist.shift().replace(/\.[^.]+$/, '');
otherwise, use
var fileNoExt = filelist.shift().replace(/\.[^.]*$/, '');
The second one matches my_crazy_file. and my_crazy_file.extension while the first only matches my_crazy_file.extension.
Here's a one-liner:
var filelist = ['file.name.ext', 'some.another.string']
filelist.shift().split('.').slice(0, -1).join('.') // 'file.name'
"is it possible to turn this code into a one-liner?"
Yes,
var fileNoExt = filelist[0].substr(0, filelist.shift().lastIndexOf('.'));
but why? It's clearer on two lines.
Related
I scrape sites for a database with a chrome extension,
need assitance with a JavaScript Clean up function
e.g
https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p
my target output is:
_60789694386.html
everything past .html needs to be removed, but since it is diffrent in each URL - i'm lost
the output is in a .csv file, in which i run a JavaScript to clean up the data.
this.values[8] = this.values[8].replace("https://www.alibaba.com/product-detail/","");
this.values[8] is how i target the column in the script. (Column 8 holds the URL)
Well, you can use split.
var final = this.values[8].split('.html')[0]
split gives you an array of items split by a string, in your case'.html', then you take the first one.
Consider using substr
this.values[8] = this.values[8].substr(0,this.values[8].indexOf('?'))
You can use split method to divide text from ? as in example.
var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
var result = link.split('?')[0].replace("https://www.alibaba.com/product-detail/","");
console.log(result);
Not sure i understood your problem, but try this
var s = 'https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p'
s = s.substring(0, s.indexOf('?'));
console.log( s );
For when you don't care about readability...
this.values[8] = new URL(this.values[8]).pathname.split("/").pop().replace(".html","");
Alternate, without using split
var link = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
var result = link.replace('https://www.alibaba.com/product-detail/', '').replace(/\?.*$/, '');
console.log(result);
You can use the regex to get it done. As of my knowledge you do something like:
var v = "https://www.alibaba.com/product-detail/_60789694386.html?spm=a2700.galleryofferlist.normalList.1.5be41470uWBNGm&s=p"
result = (v.match(/[^\/]+$/)[0]);
result = result.substring(0,result.indexOf('?'));
console.log(result); // will return _60789694386.html
Okay, so I have a filepath with a variable prefix...
C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade
... now this path will be different for whatever computer I'm working on...
is there a way to traverse the string up to say 'secc-electron\', and drop it and everything before it while preserving the rest of it? I'm familiar with converting strings to arrays to manipulate elements contained within delimiters, but this is a problem that I have yet to come up with an answer to... would there be some sort of regex solution instead? I'm not that great with regex so I wouldn't know where to begin...
What you probably want is to do a split (with regex or not):
Here's an example:
var paragraph = 'C:\\Users\\susan ivey\\Documents\\VKS Projects\\secc-electron\\src\\views\\main.jade';
var splittedString = paragraph.split("secc-electron"); // returns an array of 2 element containing "C:\\Users\\susan ivey\\Documents\\VKS Projects\\" as the first element and "\\src\\views\\main.jade" as the 2nd element
console.log(splittedString[1]);
You can have a look at this https://www.w3schools.com/jsref/jsref_split.asp to learn more about this function.
With Regex you can do:
var myPath = 'C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade'
var relativePath = myPath.replace(/.*(?=secc-electron)/, '');
The Regex is:
.*(?=secc-electron)
It matches any characters up to 'secc-electron'. When calling replace it will return the last part of the path.
You can split the string at a certain point, then return the second part of the resulting array:
var string = "C:\Users\susan ivey\Documents\VKS Projects\secc-electron\src\views\main.jade"
console.log('string is: ', string)
var newArray = string.split("secc-electron")
console.log('newArray is: ', newArray)
console.log('newArray[1] is: ', newArray[1])
Alternatively you could use path.parse(path); https://nodejs.org/api/path.html#path_path_parse_path and retrieve the parts that you are interested in from the object that gets returned.
I make a text file "foo\nbar\nbas"
When i append coke(with adding \n), then the file will be "foo\nbar\nbas\ncoke"
I want to remove the foo.
Help me!
Fo your use case that you have provided, a simple answer is split on \n, remove the first item, add the new item to the end, and join the array to form your new string.
var parts = "foo\nbar\nbas".split("\n").slice(1);
parts.push("coke");
var updated = parts.join("\n");
Other option is to use indexOf to find the first occurrence of \n and substring to select the portion of the string, then it is a simple concatenation.
var str = "foo\nbar\nbas";
var position = str.indexOf("\n")+1;
var updated = str.substring(position) + "\ncoke";
You can use simple string manipulation if your task is not complicated by further constraints. Such is as follows:
var fileContents = "foo\nbar\nbas";
// Read Text File, in this case, I have set it.
fileContents = fileContents.replace("foo\n", "");
fileContents += "\ncoke";
// Write back to file
I'm taking the following ex URL https://support.dev.mysite.com/batch/ and removing everything, but the environment (eg dev). The below code works fine.
var env = endPoint.replace("https://support.", "\n");
var envClean = env.replace(".mysite.com/batch/", "\n");
I don't like repeating myself. I would like to look for both patterns in the string and remove them all at once. MDN has a good breakdown of replace() here - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace but it doesn't mention anything about multiple arguments.
I've tried this:
var env = endPoint.replace("https://support." && ".mysite.com/batch/", "\n");
but it just parses the second arg and disregards the first.
Does anyone have a cleaner way of doing this? I'm assuming I can search for multiple patterns via REGEX, any REGEX masters out there care to help?
Cheers.
You can use regular expressions for this:
var environment = 'https://support.dev.mysite.com/batch/'
.replace(/^https:\/\/support\.|\.mysite\.com\/batch\/$/g, '');
You could chain your method:
var envClean = endPoint.replace("https://support.", "\n").replace(".mysite.com/batch/", "\n");
Or you could use regex:
var envClean = endPoint.replace(/https:\/\/support\.|\.mysite\.com\/batch\//, "\n");
And there is another solution to get dev:
var envClean = endPoint.match(/^https:\/\/support\.([^.]*)\.mysite\.com\/batch\/$/)[1];
For this specific URL pattern, why not make it really simple and use .split():
var url = 'https://support.dev.mysite.com/batch/';
var name = url.split('.')[1];
If I were using a regular expression, I would probably do it this way:
var match = url.match( /support\.(.*)\.mysite.com/ );
var name = match && match[1];
Note that you don't have to worry about the entire URL this way, only enough to do the match.
If you know that the URL will match, you can simplify that to:
var name = url.match( /support\.(.*)\.mysite.com/ )[1];
How can I use jquery on the client side to substring "nameGorge" and remove "name" so it outputs just "Gorge"?
var name = "nameGorge"; //output Gorge
No jQuery needed! Just use the substring method:
var gorge = name.substring(4);
Or if the text you want to remove isn't static:
var name = 'nameGorge';
var toRemove = 'name';
var gorge = name.replace(toRemove,'');
Using .split(). (Second version uses .slice() and .join() on the Array.)
var result = name.split('name')[1];
var result = name.split('name').slice( 1 ).join(''); // May be a little safer
Using .replace().
var result = name.replace('name','');
Using .slice() on a String.
var result = name.slice( 4 );
Standard javascript will do that using the following syntax:
string.substring(from, to)
var name = "nameGorge";
var output = name.substring(4);
Read more here: http://www.w3schools.com/jsref/jsref_substring.asp
That's just plain JavaScript: see substring and substr.
You don't need jquery in order to do that.
var placeHolder="name";
var res=name.substr(name.indexOf(placeHolder) + placeHolder.length);
var name = "nameGorge";
name.match(/[A-Z].*/)[0]
Yes you can, although it relies on Javascript's inherent functionality and not the jQuery library.
http://www.w3schools.com/jsref/jsref_substr.asp
The substr function will allow you to extract certain parts of the string.
Now, if you're looking for a specific string or character to use to find what part of the string to extract, you can make use of the indexOf function as well.
http://www.w3schools.com/jsref/jsref_IndexOf.asp
The question is somewhat vague though; even just link text with 'name' will achieve the desired result. What's the criteria for getting your substring, exactly?
How about the following?
<script charset='utf-8' type='text/javascript'>
jQuery(function($) { var a=$; a.noConflict();
//assumming that you are using an input text
// element with the text "nameGorge"
var itext_target = a("input[type='text']:contains('nameGorge')");
//gives the second part of the split which is 'Gorge'
itext_target.html().split("nameGorge")[1];
...
});
</script>