Javascript / Jquery - 從字符串中獲取數字

[英]Javascript / Jquery - Get number from string


the string looks like this

字符串看起來像這樣

"blabla blabla-5 amount-10 blabla direction-left"

How can I get the number just after "amount-", and the text just after "direction-" ?

如何在“amount-”之后獲取數字,以及在“direction-”之后的文本?

3 个解决方案

#1


17  

This uses regular expressions and the exec method:

這使用正則表達式和exec方法:

var s = "blabla blabla-5 amount-10 blabla direction-left";
var amount = parseInt(/amount-(\d+)/.exec(s)[1], 10);
var direction = /direction-([^\s]+)/.exec(s)[1];

The code will cause an error if the amount or direction is missing; if this is possible, check if the result of exec is non-null before indexing into the array that should be returned.

如果缺少數量或方向,代碼將導致錯誤;如果可能,請在索引到應返回的數組之前檢查exec的結果是否為非null。

#2


38  

This will get all the numbers separated by coma:

這將使所有數字被昏迷分開:

var str = "10 is smaller than 11 but greater then 9";
var pattern = /[0-9]+/g;
var matches = str.match(pattern);

After execution, the string matches will have values "10,11,9"

執行后,字符串匹配的值為“10,11,9”

If You are just looking for thew first occurrence, the pattern will be /[0-9]+/ - which will return 10

如果你只是第一次出現,那么模式將是/ [0-9] + / - 這將返回10

(There is no need for JQuery)

(不需要JQuery)

#3


6  

You can use regexp as explained by w3schools. Hint:

您可以使用w3schools解釋的正則表達式。暗示:

str = "blabla blabla-5 amount-10 blabla direction-left"
alert(str.match(/amount-([0-9]+)/));

Otherwize you can simply want all numbers so use the pattern [0-9]+ only. str.match would return an array.

另外,你可以簡單地想要所有數字,所以只使用模式[0-9] +。 str.match將返回一個數組。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/10/17/72506ee1e9b856674dae751056915e5b.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com