2017-08-27 67 views
0

數我有一個字符串:的Javascript正從字符串

var example = 'sorted-by-' + number; 

其中number變量可以是任意正整數。我不知道如何扭轉這個過程,不知道這個數字有多少個數字。我想從例子字符串中得到一個數字。

+3

的可能的複製[JavaScript的得到串號(https://stackoverflow.com/questions/10003683/javascript-get-number-from-string) – M0ns1f

+0

您的問題是deplicate看到這個https://stackoverflow.com/questions/10003683/javascript-get-number-from-string – M0ns1f

回答

3
var outputNumber = example.substring(10); 

這是簡單的解決方案,因爲例如串始終與 '排序逐' 開頭。

2
let num = + string.substr(10); 
1

可以使用String#replace功能來代替sorted-by-空字符串,之後左側部分轉換爲數字:

var example = 'sorted-by-' + 125; 
 
var num = +example.replace('sorted-by-', ''); 
 

 
console.log(num);

1

您可以在-拆分串並獲得最後的元素使用pop()

var example = 'sorted-by-' + 100.99 
 
var n = +(example.split('-').pop()) 
 

 
console.log(n)

0

您也可以使用regex

var number = 245246245; 
 
var example = 'sorted-by-' + number; 
 

 
var res = example.match(/^sorted-by-(\d+)/); 
 
console.log(+res[1]);