[英]Which method should I use to extract the specified data from a text?
我正在嘗試從文本中提取 CSRF 代碼。
例如,這是我的文字csrf
:
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
MarketManager.Cart.CartTotal = 0;
MarketManager.csrfCode = sd9192djsidhd72jSKkjS799;
MarketManager.UserID = 22216;
console.log(MarketWebSockets not loaded.);
});
我需要提取這個sd9192djsidhd72jSKkjS799
。 我已經使用csrf = csrf.replace(/"/g, '');
刪除引號,但我不知道如何使用這種方法來擺脫其他不必要的信息。我應該使用另一種方法嗎?
搜索 'csrfCode = ',然后從那里搜索到 ';'; 代碼是介於兩者之間的東西。
您需要的方法是 String 的.indexOf(needle)
和.indexOf(needle, fromIndex)
,以及提取字符串、一些基本數學和.substring(from, to)
。
我建議您最簡單的選擇是使用正則表達式。 這表現良好且易於使用:
// Text to be searched
var csrf = ` (function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
MarketManager.Cart.CartTotal = 0;
MarketManager.csrfCode = sd9192djsidhd72jSKkjS799;
MarketManager.UserID = 22216;
console.log(MarketWebSockets not loaded.);
;
});`
// regular expression to find "csrfCode = " and capture
// the alphanumeric string following it
var re = /csrfCode = (\w*)/s ;
// apply the regular expression
var result = re.exec( csrf );
// check and report the result
if( !result ){
console.log( "No match found")}
else{
// the captured string is stored in the result array
console.log( "Match found: [" + result[1] + "]");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.