Extracting Elements From A Variable
Solution 1:
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.
Solution 2:
var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
var trimmedUrl = url.replace('.html', '');
Solution 3:
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.
Solution 4:
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
Solution 5:
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('.') );
Post a Comment for "Extracting Elements From A Variable"