我有这个字符串,我在我的项目中使用JavaScript而且我有这个
338 km 3 heurs 28分钟
我想要的只是提取数字,我想创建一个方法,可以将每个数字放在变量中。
我试过了,但它不起作用:
var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g)
var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g)
var num = "338 km 3 heurs 28 minutes".match(/[\d]+/g)
答案 0 :(得分:3)
您可以使用array destructuring将每个数字分配给变量或常量。
注意:我使用Array#map和Number function将每个数字字符串转换为实际数字,但如果您只想要数字字符串,则可以跳过此步骤。
const [a, b, c] = "338,7 km 3 heurs 28 minutes"
.match(/\d+(:?,\d+)?/g) // match numbers with commas as decimal separator
.map((n) => Number(n.replace(',', '.'))); // convert the comma to dot, and convert to number
console.log(a);
console.log(b);
console.log(c);

答案 1 :(得分:0)
你很亲密。您的代码返回一组匹配项。您可以将每个数组项分配给它自己的变量,但为什么呢?它们都在阵列中:
Option Explicit
Sub Divide()
Dim txt As String
Dim i As Integer
Dim j As Integer
Dim Full As Variant
Dim a As Integer
Dim b As Integer
Dim stored() As Integer
txt = (CStr(ActiveCell.Value))
Full = Split(txt, ";")
a = UBound(Full)
b = a - 1
ReDim stored(b)
For i = 0 To a
stored(i) = ExtractNumber((Full(i)))
Next i
Dim primary_index As Integer
Dim primary_no As Integer
Dim primary_name As String
primary_index = Application.Match(Application.Max(stored), stored, 0)
primary_no = stored(primary_index)
primary_name = Full(primary_index)
stored(primary_index) = 0
If UBound(stored) > 1 Then
Dim secondary_index As Integer
Dim secondary_no As Integer
Dim secondary_name As String
secondary_index = Application.Match(Application.Max(stored), stored, 0)
secondary_no = stored(secondary_index)
secondary_name = Full(secondary_index)
End If
For i = 0 To 6
ActiveCell.EntireColumn.Offset(0, 1).Insert
Next i
If UBound(stored) > 2 Then
Dim names() As String
ReDim names(0 To a)
For j = 0 To a
If Not (j = primary_index Or j = secondary_index) Then
names(j) = Full(j)
End If
Next j
ActiveCell.Offset(0, 1).Value = primary_name
ActiveCell.Offset(0, 2).Value = primary_no
ActiveCell.Offset(0, 3).Value = secondary_name
ActiveCell.Offset(0, 4).Value = secondary_no
ActiveCell.Offset(0, 5).Value = names
ActiveCell.Offset(0, 6).Value = (ActiveCell.Offset(0, 8).Value - primary_no - secondary_no)
ElseIf UBound(stored) = 2 Then
ActiveCell.Offset(0, 1).Value = primary_name
ActiveCell.Offset(0, 2).Value = primary_no
ActiveCell.Offset(0, 3).Value = secondary_name
ActiveCell.Offset(0, 4).Value = secondary_no
End
Else
ActiveCell.Offset(0, 1).Value = primary_name
ActiveCell.Offset(0, 2).Value = primary_no
End
End If
End Sub