Reputation: 772
I have this simple variables
var string = 'this is string id="textID" name="textName" title="textTitle" value="textVal"';
var id, name, title, value;
I need to filter var string
and get values for this variables id, name, title, value
How to do this?
Upvotes: 1
Views: 84
Reputation: 8741
I've used this function, as all your attributes have the same form, this works:
//
// 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);
Upvotes: 2
Reputation: 3281
You can fetch the values by their indexes. Like I've done below:
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
Similarly you can do for other elements. Hope this helps..!
Upvotes: 1