I have a string 'http://this.is.my.url:007/directory1/directory2/index.html' and I need to extract the string as below. Please advice the best way
var one = http://this.is.my.url:007/directory1/directory2/index
Try this:
var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
url.replace(/\.[^.]*$/g, ''); // would replace all file extensions at the end.
// or in case you only want to remove .html, do this:
var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
url.replace(/\.html$/g, '');
The $ character when included in a regular expression matches to the end of the text string. In variant a you look start at the "." and remove everything from the this character until the end of the string. In variant 2, you reduce this to the exact string ".html". This is more about regular expressions than about javascript. To learn more about it, here is one of many nice tutorials.
var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
var trimmedUrl = url.replace('.html', '');
You just need to use replace():
var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
var one = url.replace('.html', '');
If want to ensure you only remove the .html from the end of the string use regex:
var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
var one = url.replace(/\.html$/', '');
The $ indicates that only the last characters of the string should be checked.
Using a regular expression, it replaces everything (.*) with itself from the capture group (not including the trailing .html).
var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
var one = url.replace(/(.*)\.html/, '$1');
^ ^ ^^
// Capture group ______| |__________||
// Capture ----> Get captured content
You could slice the string up to the last dot:
var url = 'http://this.is.my.url:7/directory1/directory2/index.html';
url = url.slice(0,url.lastIndexOf('.'));
//=> "http://this.is.my.url:7/directory1/directory2/index"
Or in one line:
var url = ''.slice.call(
url='http://this.is.my.url:7/directory1/directory2/index.html',
0,url.lastIndexOf('.') );
Related
I'm trying to remove all the text which falls before the last character in a Regex pattern.
Example:
rom.com/run/login.php
Becomes:
login.php
How would I go about doing this in JavaScript? I'm new to regular expressions.
To get everything after last slash, use [^\/]+$
const str = "rom.com/run/login.php";
console.log(str.match(/[^/]+$/)[0]);
You can get the result you need by searching for a literal string (just one character in fact) so there's no need to employ regular expressions which will cost you performance.
You can split the input into chunks separated by / and get the last chunk:
var input = 'rom.com/run/login.php';
var result = input.split('/').pop();
Or find the position of the last occurrence of / in the input, and get the remainder of the string that follows that position:
var input = 'rom.com/run/login.php';
var result = input.substring(input.lastIndexOf('/') + 1);
One approach is a regex replacement:
var path = "rom.com/run/login.php";
var output = path.replace(/^.*\//, "");
console.log(output);
The regex pattern ^.*/ is greedy, and will consume everything up to (and including) the last path separator. Then, we replace this match with empty string, to effectively remove it.
You could do it with Regex like this:
var url = 'rom.com/run/login.php'
var page = url.match('^.*/(.*)')[1]
console.log(page)
Or you could do it without Regex like this:
var url = 'rom.com/run/login.php'
var split = url.split('/')
var page = split[split.length-1]
console.log(page)
How to get string between two dot (last dot followed by image extension) ?
I try to filter the string will be delete then replace by '',
but my regex is wrong, how to solve it?
e.g
// a09 could be any letter
var str = 'https://s.domain.com/q1_1-0.a09.jpg';
I want to remove .a09 become
'https://s.domain.com/q1_1-0.jpg';
try to get .a09 then replace by ''
var str = 'https://s.domain.com/q1_1-0.a09.jpg';
var regexPattern = /(\.(.*?)\.(jpg|jpeg|tiff|png)$)/;
var removeString = regexPattern.exec(str);
console.log(removeString)
I would use a negated character class to make sure its the last dot before the extensions. Here is a solution specifically for jpg
Replace
\.[^.]*(\.jpg)
With
$1
In Javascript dialect:
result = subject.replace(/\.[^.]*(\.jpg)/g, "$1");
Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.
How I can get the value after last char(. ; + _ etc.):
e.g.
string.name+org.com
I want to get "com".
Is there any function in jQuery?
Use lastIndexOf and substr to find the character and get the part of the string after it:
var extension = name.substr(name.lastIndexOf(".") + 1);
Demo: http://jsfiddle.net/Guffa/K3BWn/
A simple and readable approch to get the substring after the last occurrence of a character from a defined set is to split the string with a regular expression containing a character class and then use pop() to get the last element of the resulting array:
The pop() method removes the last element from an array and returns that element.
See a JS demo below:
var s = 'string.name+org.com';
var result = s.split(/[.;+_]/).pop();
console.log(result);
to split at all non-overlapping occurrences of the regex by default.
NOTE: If you need to match ^, ], \ or -, you may escape them and use anywhere inside the character class (e.g. /[\^\-\]\\]/). It is possible to avoid escaping ^ (if you do not put it right after the opening [), - (if it is right after the opening [, right before the closing ], after a valid range, or between a shorthand character class and another symbol): /[-^\]\\]/.
Also, if you need to split with a single char, no regex is necessary:
// Get the substring after the last dot
var result = 'string.name+org.com'.split('.').pop();
console.log(result);
Not jQuery, just JavaScript: lastIndexOf and substring would do it (not since the update indicating multiple characters). As would a regular expression with a capture group containing a character class followed by an end-of-string anchor, e.g. /([^.;+_]+)$/ used with RegExp#exec or String#match.
E.g. (live copy | source):
var match = /([^.;+_]+)$/.exec(theStringToTest),
result = match && match[1];
var s = "string.name+org.com",
lw = s.replace(/^.+[\W]/, '');
console.log(lw) /* com */
this will also work for
string.name+org/com
string.name+org.info
You can use RegExp Object.
Try this code:
"http://stackoverflow.com".replace(/.*\./,"");
I'll throw in a crazy (i.e. no RegExp) one:
var s = 'string.name+org.com';
var a = s.split('.'); //puts all sub-Strings delimited by . into an Array
var result = a[a.length-1]; //gets the last element of that Array
alert(result);
EDIT: Since the update of the question is demanding mutiple delimiters to work this is probably not the way to go. Too crazy.....
use javascript function like
url.substr(url.length - 3);
maybe this is too late to consider, this codes works fine for me using jquery
var afterDot = value.substr(value.lastIndexOf('_') + 1);
You could just replate '_' to '.'
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
I'm trying to search for '[EN]' in the string 'Nationality [EN] [ESP]', I want to remove this from the string so I'm using a replace method, code examaple below
var str = 'Nationality [EN] [ESP]';
var find = "[EN]";
var regex = new RegExp(find, "g");
alert(str.replace(regex, ''));
Since [EN] is identified as a character set this will output the string 'Nationality [] [ESP]' but I want to remove the square brackets aswell. I thought that I could escape them using \ but it didn't work
Any advice would be much appreciated
Try setting your regex this way:
var regex = /\[EN\]/g;
If you just want to replace a single instance of it you can just str = str.replace("[EN] ", ""); otherwise; var find = "\\[EN\\]";.