Retrieving items from a variable

I have a string ' http: //this.is.my.url: 007 / directory1 / directory2 / index.html ' and I need to extract the string as shown below. Please advise the best way.

var one = http: //this.is.my.url: 007 / directory1 / directory2 / index

+3


source to share


5 answers


Try the following:

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 the end of the text string. In option a, you are looking at "." and remove everything from that character to the end of the line. In option 2, you will reduce this to the exact ".html" string. This is more about regular expressions than javascript. To learn more about it, here is one of the many enjoyable tutorials .

+7


source


You just need to use replace()

:

var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
var one = url.replace('.html', '');

      

If you want you to only remove .html

from the end of the line, use a regex:



var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
var one = url.replace(/\.html$/', '');

      

$

specifies to check only the last characters of the string.

+3


source


var url = 'http://this.is.my.url:007/directory1/directory2/index.html';
var trimmedUrl = url.replace('.html', '');

      

+3


source


You can slice

line up to the last point:

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('.')  );

      

+2


source


Using regex, it replaces all ( .*

) with itself from the capturing group (not including the final one .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

      

+2


source







All Articles