Madav
Madav

Reputation: 311

How to extract a string from another string based up on two character comparison in javascript

In javascript, I have a string that looks like:

var str = 'id=126e-90:vj=34566f:ff=1998452'.

I want to get the value of id out of it. That is, 126e-90.

Could any one please suggest me the better way of achieving it. Thank you

Upvotes: 2

Views: 90

Answers (4)

madox2
madox2

Reputation: 51861

You can use regular expression (considering that your parameter could be anywhere in the string):

var regex = /(^|:)id=([^:]*)($|:)/;
regex.exec('id=126e-90:vj=34566f:ff=1998452')[2]; // 126e-90
regex.exec('vj=34566f:id=126e-90:ff=1998452')[2]; // 126e-90
regex.exec('vj=34566f:ff=1998452:id=126e-90')[2]; // 126e-90

Upvotes: 0

arman1991
arman1991

Reputation: 1166

There is a few solutions to solve your problem. This is also one of possible ways to get the value of id. The idea is to find the first index of : and = in your id via indexOf() method, and then to use substring() method to get the id value between these indexes.

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p> 

<script>
var txt = "id=126e-90:vj=34566f:ff=1998452";
var indexColon = txt.indexOf(':'); //find index of ':'
var indexEqual = txt.indexOf('=') + 1; //find index of '='
var rez = txt.substring(indexEqual ,indexColon);
document.getElementById("demo").innerHTML = rez;
</script>

</body>
</html>

Upvotes: 1

Nonemoticoner
Nonemoticoner

Reputation: 648

I'd rather use Regular Expression:

var id = "id=126e-90:vj=34566f:ff=1998452".match(/id=(.*?):/)[1];

That will give you the expected value.

Upvotes: 2

jrader
jrader

Reputation: 669

You are looking for the split method. First, you'll want to split by : and then iterate through each key/value pair to get your id

var id;
var str = 'id=126e-90:vj=34566f:ff=1998452'
var pairs = str.split(':');

pairs.forEach(function(pair) {
    var key = pair.split('=')[0];
    var value = pair.split('=')[1];

    if (key === 'id') {
        id = value;
    }
});

Upvotes: 4

Related Questions