如何在javascript中使用正则表达式在两个其他字符串之间找到一个字符串?

时间:2023-01-25 07:07:29

In javascript I have the string of the following format:

在javascript中我有以下格式的字符串:

var string = "directory/filename.extension";

and I want to retrieve the substring filename. I.e from the string images/panda.jpg I want to extract just panda

我想检索子串文件名。我从字符串images / panda.jpg我想提取熊猫

4 个解决方案

#1


0  

You could split the string on these characters if it's always this consistent.

如果它始终保持一致,您可以在这些字符上拆分字符串。

var r = 'images/panda.jpg'.split(/[/.]/)[1]
console.log(r) //=> "panda"

#2


1  

You could try the below.

你可以尝试以下。

> var s = "directory/filename.extension";
undefined
> s.match(/[^.\/]+(?=\.)/)
[ 'filename',
  index: 10,
  input: 'directory/filename.extension' ]
> s.match(/[^.\/]+(?=\.)/)[0]
'filename'
> "images/panda.jpg".match(/[^.\/]+(?=\.)/)[0]
'panda'

#3


0  

For example:

例如:

var myRe = /\/([^.]+)./;
var result = myRe.exec("images/panda.jpg")[1];

#4


0  

var result = string.match(/.+?\/(.+?)\..+/);
var filename = result[1];

Hope this helps.

希望这可以帮助。

#1


0  

You could split the string on these characters if it's always this consistent.

如果它始终保持一致,您可以在这些字符上拆分字符串。

var r = 'images/panda.jpg'.split(/[/.]/)[1]
console.log(r) //=> "panda"

#2


1  

You could try the below.

你可以尝试以下。

> var s = "directory/filename.extension";
undefined
> s.match(/[^.\/]+(?=\.)/)
[ 'filename',
  index: 10,
  input: 'directory/filename.extension' ]
> s.match(/[^.\/]+(?=\.)/)[0]
'filename'
> "images/panda.jpg".match(/[^.\/]+(?=\.)/)[0]
'panda'

#3


0  

For example:

例如:

var myRe = /\/([^.]+)./;
var result = myRe.exec("images/panda.jpg")[1];

#4


0  

var result = string.match(/.+?\/(.+?)\..+/);
var filename = result[1];

Hope this helps.

希望这可以帮助。