2013-10-24 89 views
1

我有這個簡單的變量過濾字符串和返回值

var string = 'this is string id="textID" name="textName" title="textTitle" value="textVal"'; 
var id, name, title, value; 

我需要過濾var string並獲得值這個變量id, name, title, value
如何做到這一點?

+4

什麼是你的企圖? 「詢問代碼的問題必須證明對所解決問題的最小理解」 – ComFreek

+0

我不知道我應該使用什麼函數。 –

+0

你可能想要使用正則表達式,看看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions –

回答

2

我用這個功能,因爲你所有的屬性具有相同的形式,這個工程:

// 
// inputs: 
// strText: target string 
// strTag: tag to search, can be id, name, value, title, ... 
// 
function getTagValue(strText, strTag) 
{ 
    var i, j, loffset = strTag.length + 2; 
    i = strText.indexOf(strTag + '="', 0); 
    if(i >= 0) 
    { 
    j = strText.indexOf('"', i + loffset); 
    if(j > i) 
    { 
     return strText.substring(i + loffset, j); 
    } 
    } 
    return ""; 
} 

// 
// main: 
// 
var string = 'this is string id="textID" name="textName" title="textTitle" value="textVal"'; 
var id, name, title, value; 
console.log(string); 

id = getTagValue(string, "id"); 
console.log(id); 

name = getTagValue(string, "name"); 
console.log(name); 

title = getTagValue(string, "title"); 
console.log(title); 

value = getTagValue(string, "value"); 
console.log(value); 
1

您可以通過索引獲取值。像我這樣做:

var stringValue = 'this is string id="textID" name="textName" title="textTitle" value="textVal"'; 


var indexOfID=stringValue.indexOf('id'); // find the index of ID 

var indexOfEndQuoteID=stringValue.indexOf('"',(indexOfID+4)); // find the index of end quote 

var ID=stringValue.substring((indexOfID+4),(indexOfEndQuoteID)); // fetch the string between them using substring 

alert(ID); // alert out the ID 

同樣,你可以爲其他元素做。希望這可以幫助..!

+0

很好,但是在'indexOfID + 4'中有什麼意義'+ 4'? –

+0

因爲您必須提取您需要跳過的第一個結束引號.. indexOfID + 4會告訴indexOf()在第一個引號之後開始查找引用。您是否接收到我?你可以參考這個http://www.w3schools.com/jsref/jsref_indexof_array.asp – writeToBhuwan

+0

由於索引將被提取在「我」的「ID」..你將不得不跳過D =「(三個字符) – writeToBhuwan