Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript正则表达式从特定单词获取数字部分_Javascript_Jquery_Regex - Fatal编程技术网

Javascript正则表达式从特定单词获取数字部分

Javascript正则表达式从特定单词获取数字部分,javascript,jquery,regex,Javascript,Jquery,Regex,假设我们有一个包含这些类的元素:“floatleftitem4” 如果我想将数字“4”保存到“item4”中的一个变量中,我该怎么做 我想我会使用此模式“/item(\d+/”,但我是否使用替换或匹配以及如何使用?您可以这样使用匹配: var str = "item4", num = +str.match(/item(\d+)/)[1]; // => 4 我用一元+转换成一个数字。您可以改用parseInt或Number构造函数。您需要使用.match(…)与捕获组匹配 "flo

假设我们有一个包含这些类的元素:“floatleftitem4”

如果我想将数字“4”保存到“item4”中的一个变量中,我该怎么做


我想我会使用此模式“/item(\d+/”,但我是否使用替换或匹配以及如何使用?

您可以这样使用匹配:

var str = "item4",
    num = +str.match(/item(\d+)/)[1]; // => 4

我用一元
+
转换成一个数字。您可以改用
parseInt
Number
构造函数。

您需要使用
.match(…)
与捕获组匹配

"floatLeft item4".match(/item(\d+)/)
// Result: ["item4", "4"]
使用替换:

“floatLeft item4”。替换(/.*item(\d+/,“$1”)

使用匹配:

“floatLeft item4”。匹配(/item(\d+/)[1]

执行官(非常喜欢匹配)

/item(\d+)/.exec(“floatLeft item4”)[1]

使用split(同样,与match类似):

“floatLeft item4”。拆分(/item(\d+/)[1]


虽然并非所有浏览器都支持
split
方法(如IE…)

但您不应该在
var str = "item4",
    num = (str.match(/item([0-9]+)/)||[])[1]; // if no match, `match` will return null therefore the `|| []` (or empty array). 

console.log(num); // "4" (typeof num === "string")

console.log(+num) // 4 (typeof num === "number")