2016-02-28 112 views
0

我想擺脫我努力嘗試不了的逗號。我查看了互聯網上的所有源代碼。每個人都說.replace(一些正則表達式) - >我試過那個,它沒有工作,node.js和jquery的錯誤是.replace()不是函數。爲什麼我會收到逗號?

我解析這個數據從JSON文件和客戶端是jQuery與ajax。

輸出:

我想我的正則表達式的功能是錯誤的,我需要它可以掃描我的JSON文件,然後找到網址,AKA與FTP/HTTP/HTTPS/WWW等啓動功能,

謝謝!

+0

告訴我們您的正則表達式功能,您試圖解析數據,也就是它只是逗號,你需要擺脫的? – thatOneGuy

+0

你可以顯示你想分析的數據嗎?它的字符串是正確的?或者你是加載整個JSON文件作爲一個字符串和匹配? –

+0

是的,它只是我需要擺脫的逗號,因爲我需要解析來自JSON數據的URL,我將使用它們。 –

回答

0

以下是從給定的JSON對象中提取URL的功能。

注意:這個函數也可以在node.js上運行! :)

function extractUrls(data) { 
     var s = JSON.stringify(data); 
     var regx = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; 

     return s.match(regx); 
    } 

而以下是您想通過掃描數據(它的結構並不重要)

var data = [{ 
    "id": 4797492459, 
    "text": "She was lucky that she could use href=\"http://www.google.com\" right?", 
    "user": { 
    "url": "http://whatever.com" 
    } 
}, { 
    "id": 4797490987, 
    "text": "She was unlucky that she could not use href=\"http://www.google.in\" right?", 
    "user": { 
    "url": "http://another-whatever.com" 
    } 
}]; 

然後下面的代碼行

var urlArray = extractUrls(data); 

console.log(urlArray); 

將產生陣列

[ 
    "http://www.google.com", 
    "http://whatever.com", 
    "http://www.google.in", 
    "http://another-whatever.com" 
] 

注意:直到這裏的所有東西都可以在node.js中使用。

JQuery示例。 下面是一個小提琴手例如

https://jsfiddle.net/wdkdwk2g/1/

完全提琴手代碼 JS

var data = [{ 
    "id": 4797492459, 
    "text": "She was lucky that she could use href=\"http://www.google.com\" right?", 
    "user": { 
    "url": "http://whatever.com" 
    } 
}, { 
    "id": 4797490987, 
    "text": "She was unlucky that she could not use href=\"http://www.google.in\" right?", 
    "user": { 
    "url": "http://another-whatever.com" 
    } 
}]; 

function extractUrls(data) { 
    var s = JSON.stringify(data); 
    var regx = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; 

    return s.match(regx); 
} 

var urlArray = extractUrls(data); 

console.log(urlArray); 

urlArray.forEach(function(url) { 
    $('ul').append('<li>' + url + '</li>'); 
}); 

HTML

<ul></ul> 

輸出

enter image description here

我希望這是你在找什麼。

讓我知道你是否需要別的東西!

:)

+0

問題是數據在數據中很長,並且可能是一個URL,我需要它們的列表,我需要我的代碼來掃描它們並找到它們,我需要所有這些數據。所以,我需要一個迭代代碼,它可以找到所有這些代碼並刪除逗號。我分享的代碼找到了所有這些代碼,我不能擺脫逗號。 –

+0

噢...好的。現在我懂了。我在回家的路上。我會在大約半個小時內找到解決方案! –

+0

好吧,假設這是你的數據'[{0 {0} {0} {id}:4797492459, 「text」:「她很幸運可以使用href = \」http://www.google.com \「對不對? 「user」:{「url」:「http://whatever.com」} },{ 「id」:4797490987, 「text」:「她很倒黴,她無法使用href = \」http ://www.google.in「right?」, 「user」:{「url」:「http://another-whatever.com」} }]'並且你想要下面的輸出'['http: //www.google.com'''http://whatever.com'''http://www.google.in','http://another-whatever.com'] .... ....是這個對? –

0
var str1 = ".edu,http,,our.risd.edu,,,, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,"; 

var str2 = str1.replace(/,/g, ''); 

console.log(str2); 

記「G」的正則表達式的結束標誌

相關問題