2016-11-04 28 views
0

我有一個像下面的輸入值:如何從句子中獲得特定單詞?

<input type="text" value: "Part: PT001 Invoice: 1234" /> 

我需要的是我想從輸入的值單獨的部件號「PT001」 ..

注:PT001是動態獲取價值...

感謝您的想法...

+0

jQuery不是必需的,你需要的是一個正則表達式,或者,如果字符串是一致的,甚至可能只是字符串分裂。 – Adam

+0

@Adam然後你如何得到這個看看答案...匹配函數也來自使用js文件..我認爲你不擅長jquery和javascript – rJ7

+0

在HTML 5中,定製屬性的前綴是完全有效的數據 - 例如並使用$(this).data('partNo' ); – SDK

回答

2

使用String#match法正則表達式/\bPart:\s?(\S+)/並獲得捕獲組值。

console.log(
 
    $('input').val().match(/\bPart:\s?(\S+)/)[1] 
 
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" value="Part: PT001 Invoice: 1234" />

1

假設字符串模式仍然是所有情況下都是相同 -

舉一個id你的文本框

<input type="text" id="myTb" value="Part: PT001 Invoice: 1234" /> 

然後使用jQuery:(長版的爲了簡單起見)

var full_string = $('#myTb').val(); 
var explode = full_string.split(':'); // split the string based on : 

// explode[0] will contain "Part" 
// explode[1] will contain " PT001 Invoice" 
// explode[3] will contain " 1234" 

var part_explode = explode[1].split(" "); // split by blank space 

// similarly, part_explode[0] will be blank space 
// part_explode[1] will contain "PT001" 
// part_explode[2] will contain "Invoice" 
console.log(part_explode[1]); // should be PT001 

DEMO

0

如果PT是一致的,然後使用:

$('input').val().match(/PT\d+/); 

它將返回PT和1個或多個數字。即PT100

+0

沒有PT也不一致,它會改變 – rJ7

相關問題