Cut off extension of filename [duplicate] - javascript

This question already has answers here:
Regex for everything before last forward or backward slash
(3 answers)
Closed 5 years ago.
I have a list of filenames like
index.min.html
index.dev.html
index.min.js
index.dev.js
There.are.also.files.with.multiple.dots.and.other.extension
I want to cut off the extensions of the filenames, but the problem is that I can only use match for this task.
I tried many regular expressions looking like "index.min.html".match( /^((?!:(\.[^\.]+$)).+)/gi ); to select the filename without the last dot and extension, but they selected either the hole filename, nothing or the part before the first dot. Is there a way to select only the filename without extension?

Why regex? Simple substring expressions make this a lot simpler:
var filename = 'index.something.js.html';
alert(filename.substr(0, filename.lastIndexOf(".")));

I'd go for
/(.+)\..+$/mi
demo # regex101
See the demo, especially the matches. It only gives you the filename without the last . and the characters afterwards.

How about this one: (.*)\.[^\.]+
See http://regex101.com/r/xI6qM0

A simpler solution would be to just slice off the last element:
var a = "index.min.html";
var b = a.split('.').slice(0, -1).join('.');
Or, even better, using JavaScript's String function substr:
var b = a.substr(0, a.lastIndexOf("."));
Why do you have to use match?

Could do the trick, too:
function baseName(str) {
if (typeof str !== 'string') return;
var frags = str.split('.')
return frags.splice(0,frags.length-1).join('.');
}
Repl:http://repl.it/OvI
jsPerf: http://jsperf.com/string-extension-splits
Result:
substr is the fastest of all options in this thread. Kudos to the other guys.

Related

Javascript Regex - Match everything after string [duplicate]

This question already has answers here:
Remove querystring from URL
(11 answers)
Closed 6 years ago.
I'm trying to use JS regex to drop everything after a string in my url. For example www.myurl/one/two/three/?a=b&c=d I want to drop everything after the string "three/". How would I write a regex to match this?
Try this one:
function getPathFromUrl(url) {
return url.split("?")[0];
}
var url = 'www.myurl/one/two/three/?a=b&c=d';
var result = getPathFromUrl(url);
alert(result);
Here's one quick way.
var str = 'www.myurl/one/two/three/?a=b&c=d'
var newStr = str.replace(/(.*\/three\/).*/, '$1')
alert(newStr)
Use built-in ability to manipulate URLs.
var a = document.createElement('a');
a.href = "http://www.myurl/one/two/three/?a=b&c=d";
a.search = '';
console.log(a.href);
Notes:
The search property of the a element refers to the portion starting with the question mark.
The http:// is required here; otherwise, the URL will be interpreted as relative to the current URL.
If you would prefer to use a regexp, then you could erase everything starting with the question mark:
"www.myurl/one/two/three/?a=b&c=d".replace(/\?.*/, '')
Or, you could match what you DO want to keep, such as everything up to the question mark, using:
"www.myurl/one/two/three/?a=b&c=d".match(/.*(?=\?)/)[0]
You need the [0] since match returns an array, whose first element is the entire match. The ?= here is a look-ahead. Actually that is the same as
"www.myurl/one/two/three/?a=b&c=d".match(/[^?]+/)[0]
Or, if you want to match up to three/ specifically:
"www.myurl/one/two/three/?a=b&c=d".match(/.*three\//)[0]
Or basicaly with methods of String and Array :
var string = "www.myurl/one/two/three/?a=b&c=d";
var array = string.split('/');
array.pop();
var result = array.join("/");
console.log(result); //www.myurl/one/two/three

I am trying to figure out a regex in JavaScript for removing any strings before the dot [duplicate]

This question already has answers here:
How can I get file extensions with JavaScript?
(36 answers)
Closed 7 years ago.
I am looking for some help with Regex syntax. I tried many ways to make the syntax for this case, but nothing seems to work. Could someone help me with this?
So I have a case where I am trying to replace everything before the "." symbol in this string,
example_ so.myname
I successfully removed all the strings before the "." using this expression:
var removeStrBeforeDot = params.value.replace(/(\<b\>|\<nobr\>)[a-z]*\./g, "");
removeStrBeforeDot = removeStrBeforeDot.replace(/\(.*\)\<\/b\>/g, " ");
But the issue with this expression is, this works when there is only letters before the dot and doesn't work when there are symbols like , space, etc. Like for example, example so.myname has a space and a "_" which is not working in this case. What I like to do is keep it more generic and remove any string before the "." to be removed. Any help could be greatly appreciable.
Thanks!
One solution :
var str = 'example_ so.myname';
var result = str.replace(/[^.]*.(.*)/g , '$1');
console.log(result);
document.getElementById('el').innerHTML = result;
<div id='el'></div>
Another solution : most rapid, and less expensive !
var str = 'example_ so.myname';
var result = str.slice(str.indexOf('.')+1)
console.log(result);
document.getElementById('el').innerHTML = result;
<div id='el'></div>
This should work. It gets the position of the first dot and then collects the characters in the string from that point forward.
var dot = str.indexOf('.');
var afterDot = str.substr(dot+1);
Don't use a regex if you can do it with a simpler approach.
You can do like this:
st = 'example_ so.myname';
re = str.replace(/^.*\.+/g , '');
console.log(re)
I guess split is probably the easiest way:
alert("example_ so.myname".split(/\./)[1]);

javascript: is there any elegant way to check if string contains any of characters given in an array [duplicate]

This question already has answers here:
Call a function if a string contains any items in an array
(3 answers)
Closed 8 years ago.
I have a string in my JavaScript code (plain JavaScript, no jQuery or any other libs involved). And also I have an array which contains characters to be found in a string. I need to check if string contains any of those characters. Of course, it could be done with temporary variable like found and array elements iteration.
But is there any way to write nice and compact code? Just in case, I use ES5 (IE9+).
I want to achieve something like
var str = "Here is the string",
chars = ['z','g'];
if (str.containsAnyOf(chars)) {
...
}
What is the best way to write that piece of code?
You can use Array.prototype.some, like this
if (chars.some(function(c) { return str.indexOf(c) !== -1; })) {
// Atleast one of the characters is present
};
Consider using regular expression:
var str = "Here is the string",
chars = ['z','g'];
// constructs the following regexp: /[zg]/
if (new RegExp("[" + chars.join('') + "]").test(str)) {
alert("Contains!");
}

replace '\n' in javascript [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Fastest method to replace all instances of a character in a string [duplicate]
(14 answers)
Closed 1 year ago.
I'm trying to do replace in JavaScript using:
r = "I\nam\nhere";
s = r.replace("\n"," ");
But instead of giving me
I am here
as the value of s,
It returns the same.
Where's the problem??
As stated by the others the global flag is missing for your regular expression. The correct expression should be some thing like what the others gave you.
var r = "I\nam\nhere";
var s = r.replace(/\n/g,' ');
I would like to point out the difference from what was going on from the start.
you were using the following statements
var r = "I\nam\nhere";
var s = r.replace("\n"," ");
The statements are indeed correct and will replace one instance of the character \n. It uses a different algorithm. When giving a String to replace it will look for the first occurrence and simply replace it with the string given as second argument. When using regular expressions we are not just looking for the character to match we can write complicated matching syntax and if a match or several are found then it will be replaced. More on regular expressions for JavaScript can be found here w3schools.
For instance the method you made could be made more general to parse input from several different types of files. Due to differences in Operating system it is quite common to have files with \n or \r where a new line is required. To be able to handle both your code could be rewritten using some features of regular expressions.
var r = "I\ram\nhere";
var s = r.replace(/[\n\r]/g,' ');
use s = r.replace(/\\n/g," ");
Get a reference:
The "g" in the javascript replace code stands for "greedy" which means the replacement should happen more than once if possible
The problem is that you need to use the g flag to replace all matches, as, by default, replace() only acts on the first match it finds:
var r = "I\nam\nhere",
s = r.replace(/\n/g,' ');
To use the g flag, though, you'll have to use the regular expression approach.
Incidentally, when declaring variables please use var, otherwise the variables you create are all global, which can lead to problems later on.
.replace() needs the global match flag:
s = r.replace(/\n/g, " ");
It's working for me:
var s = r.split('\\n').join(' ');
replaceAll() is relative new, not supported in all browsers:
r = "I\nam\nhere";
s = r.replaceAll("\n"," ");
You can use:
var s = r.replace(/\n/g,' ').replace(/\r/g,' ');
because diferents SO use diferents ways to set a "new line", for example: Mac Unix Windows, after this, you can use other function to normalize white spaces.
Just use \\\n to replace it will work.
r.replace("\\\n"," ");
The solution from here worked perfect for me:
r.replace(/=(\r\n|\n|\r)/gm," ");

javascript - split without losing the separator [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript Split without losing character
I have a string:
"<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>"
I want to separate all instances of "abcdefg" into an array like this:
["<foo>abcdefg</bar>", "<foo>abcdefg</bar>", "<foo>abcdefg</bar>", "<foo>abcdefg</bar>"];
I try:
var str="<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>";
var Array_Of_FooBars = str.split("</bar>");
alert(Array_Of_FooBars);
But it returns:
["<foo>abcdefg", "<foo>abcdefg", "<foo>abcdefg", "<foo>abcdefg",]
It is removing the separator ''. I don't want that.
How can I use split and not lose the separators from the string?
Thanks.
Ken
Try this. It's not a perfect solution, but it should work in most cases.
str.split(/(?=<foo>)/)
That is, split it in the position before each opening tag.
EDIT: You could also do it with match(), like so:
str.match(/<foo>.*?<\/bar>/g)
It seems that you would most likely want to use match:
var s = "<foo>abcd1efg</bar><foo>abc2defg</bar><foo>abc3defg</bar><foo>abc4defg</bar>"
s.match(/(<foo>.+?<\/bar>)/g)
// =>["<foo>abcd1efg</bar>", "<foo>abc2defg</bar>", "<foo>abc3defg</bar>", "<foo>abc4defg</bar>"]
You could just iterate over a simple regular expression and build the array that way:
var x = new RegExp('<foo>(.*?)</bar>', 'ig'),
s = "<foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar><foo>abcdefg</bar>",
matches = [];
while (i = x.exec(s)) {
matches.push(i[0]);
}
Just realized using String.match() would be better; this code would be more useful for matching the contents inside the tags.
Use positive lookahead so that the regular expression asserts that the special character exists, but does not actually match it:
string.split(/<br \/>(?=&#?[a-zA-Z0-9]+;)/g);

Categories

Resources