过滤字符串和返回值

时间:2013-10-24 18:49:17

标签: javascript jquery

我有这个简单的变量

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

我需要过滤var string并获取此变量的值id, name, title, value
怎么做?

2 个答案:

答案 0 :(得分: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 :(得分: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

同样,你可以为其他元素做。希望这会有所帮助..!