0

I am searching for some regexp which remove the .html extension of a string.

I already found these two for some reason they don't work:

var path = './views/contacts/node/item.html';
var otherPath = path;
path.replace(/\.[^/.]+$/, '');
console.log(path);
// returns ./views/contacts/node/item.html
otherPath.replace(/(.*)\.[^.]+$/, '');
console.log(otherPath);
// also returns ./views/contacts/node/item.html

Any idea what's wrong?

3 Answers 3

2

Your original regex works, you just weren't capturing the return result. Both of the folowing will work:

path = path.replace(/\.[^/.]+$/, '');

path = path.replace(/\.html$/, '');

http://jsfiddle.net/AE2BY/

Sign up to request clarification or add additional context in comments.

3 Comments

Perhaps you could also elaborate on what the original regex's were trying to do and why they weren't working?
I’d change that to /\.html$/ to make sure it only captures extensions, but it’s the right method.
they should remove the file extensions
1
path = path.replace(/\.html$/, '');

Assuming the .html extension is at the end of the string, always.

As for what's wrong with the regexes you mention -- they're incorrect and would never match the sample string you gave.

Comments

1
var path = './views/contacts/node/item.html';
var otherPath = path.replace(/(\.html).*?$/, '');

console.log(otherPath) // './views/contacts/node/item'

This should remove everything after and including ".html".

The reason why you weren't getting what you wanted from the functions you listed above is because you were console.log'ing the wrong variable. Change:

var path = './views/contacts/node/item.html';
var otherPath = path;
path.replace(/\.[^/.]+$/, '');
console.log(path);

To:

var path = './views/contacts/node/item.html';
var otherPath = path.replace(/\.[^/.]+$/, '');
console.log(otherPath);

Comments

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.