javascript查找字符串的一部分

标签 javascript string parsing

我不太习惯 Javascript,所以我在处理字符串时遇到了问题...

如果我有类似/folder1/folder2/folder3/的东西,我该如何解析它以便我最终只得到当前文件夹,例如“文件夹 3”?

谢谢!

最佳答案

var folderName = str.match(/(folder\d+)\/$/)[1];

应该这样做。

正则表达式的解释:

(      -> Start of capture group. We want a capture group because we just want 
          the folder name without the trailing slash.           
folder -> Match the string "folder"
\d+    -> Match one or more digits
)      -> End of capture group. This lets us capture strings of the form 
          "folderN", where N is a number.              
\/     -> Escape forward slash. We have to escape this because / is used to 
          represent the start and end of a regex literal, in Javascript.              
$      -> Match the end of the string.

我们选择数组的第二个元素(在索引 1 处)的原因是因为第一个元素包含匹配的完整字符串。这不是我们想要的;我们只想要捕获组。我们只有一个我们捕获的组,所以这是第二个元素。

关于javascript查找字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15579912/

相关文章:

iphone - iPhone 的 CSS 解析库

spring - 如何解析和修改build.gradle.kts Kotlin Gradle构建脚本?

javascript - Firebase:从另一个对象检索数据

java - 在java中查找字符串的所有大写字母

java - 切换 Activity 并将字符串作为额外内容发送到另一个 Activity

javascript - 如何解析和提取javascript类方法?

javascript - 忽略 SetInterval 函数期间的错误并继续

javascript - 单击鼠标选择所有 DIV 文本

javascript - 如何在 Node js中设置 Node 计划作业,使其在服务器重新启动后不会销毁

java - input.read() 函数。堆叠while循环