我正在搜索一些删除字符串.html扩展名的正则表达式。
我已经发现这两个因为某些原因它们不起作用了:
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
知道什么是错的吗?
答案 0 :(得分:2)
您的原始regex
有效,您只是没有捕获返回结果。下面两个都有用:
path = path.replace(/\.[^/.]+$/, '');
path = path.replace(/\.html$/, '');
答案 1 :(得分:1)
path = path.replace(/\.html$/, '');
假设.html扩展名在字符串的末尾,总是。
至于你提到的正则表达式有什么问题 - 它们是不正确的,永远不会与你提供的样本字符串相匹配。
答案 2 :(得分:1)
var path = './views/contacts/node/item.html';
var otherPath = path.replace(/(\.html).*?$/, '');
console.log(otherPath) // './views/contacts/node/item'
这应删除“.html
”之后的所有内容。
你没有从上面列出的函数中得到你想要的东西的原因是因为你console.log
错误的变量。变化:
var path = './views/contacts/node/item.html';
var otherPath = path;
path.replace(/\.[^/.]+$/, '');
console.log(path);
要:
var path = './views/contacts/node/item.html';
var otherPath = path.replace(/\.[^/.]+$/, '');
console.log(otherPath);