2013-10-24 71 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