2

What's the fastest method, to remove a specific extension from a String by not using regexp (.html, .htm, .xml or whatever you feed it with) ?

I need this to convert ~500 strings <1s at once.

example:

var myURL  = 'home/johndoe/likes/pepsico.html' 
var result = 'home/johndoe/likes/pepsico'

EDIT :

      var alias = window.location.pathname //'/home/johndoe/likes/pepsico.html' 

      alias = alias.substr(alias.indexOf('/') + 1)
      alias = alias.substr( 0, alias.lastIndexOf('.') );

how can i optimize this ?

3
  • Are regular expressions too slow? How long does your solution take so far? Have you had a look at string functions? (developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…) Commented Aug 1, 2011 at 9:09
  • somebodfy told me, that regexp is a slow way and i should not use it ? O_o Commented Aug 1, 2011 at 9:11
  • 1
    Yes, regular expressions are slow compared to other string functions, but they might still be fast enough for your job. Implement something, profile it and then, if it is too slow, search for a faster solution. Commented Aug 1, 2011 at 9:13

3 Answers 3

4

You don't even need a regular expression to do the job:

var myURL  = 'home/johndoe/likes/pepsico.html',
    myURL  = myURL.substr( 0, myURL.lastIndexOf('.') );

console.log( myURL );  // "home/johndoe/likes/pepsico"
Sign up to request clarification or add additional context in comments.

1 Comment

thank you (all) - this is my result (see above) - how can i optimize this ?
2
var myURL  = 'home/johndoe/likes/pepsico.html';
var result = myURL.substr(0, myURL.lastIndexOf("."));
// .substring() also works

Note: the above examples do not check if there is no . in the string.

Comments

2

Make use of : JavaScript lastIndexOf() Method with JavaScript substring() Method

var myURL  = 'home/johndoe/likes/pepsico.html',
myURL  = myURL.substring(0, myURL.lastIndexOf('.'));
alert(myURL);

1 Comment

The answer would be perfect if those links would refer MDC instead of w3fools.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.