从变量中提取元素
我有一个字符串’ http://this.is.my.url:007 / directory1 / directory2 / index.html ‘,我需要提取字符串,如下所示。 请建议最好的方法
var one = http://this.is.my.url:007 / directory1 / directory2 / index
试试这个:
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, '');
包含在正则表达式中的$字符与文本字符串的末尾匹配。 在变体a中,你看起来是“。” 并删除此字符中的所有内容,直到字符串结尾。 在变体2中,您将其减少为精确的字符串“.html”。 这更多是关于正则表达式而不是关于javascript。 要了解有关它的更多信息,这里有许多很好的教程 。
var url = 'http://this.is.my.url:007/directory1/directory2/index.html'; var trimmedUrl = url.replace('.html', '');
你只需要使用replace()
:
var url = 'http://this.is.my.url:007/directory1/directory2/index.html'; var one = url.replace('.html', '');
如果想确保只从字符串末尾删除.html
,请使用正则表达式:
var url = 'http://this.is.my.url:007/directory1/directory2/index.html'; var one = url.replace(/\.html$/', '');
$
表示只应检查字符串的最后一个字符。
使用正则表达式,它将自己的所有内容( .*
)替换为捕获组(不包括尾随的.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
您可以将字符串slice
到最后一个点:
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"
或者在一行中:
var url = ''.slice.call( url='http://this.is.my.url:7/directory1/directory2/index.html', 0,url.lastIndexOf('.') );