multigoodverse
multigoodverse

Reputation: 8072

Extracting a part from a string in Javascript

I have a string like this LatLng(41.3371, 19.81717)stored in variable a But I only need the number 41.3371 to make some further calculation. Any idea on how I can extract the number?

Upvotes: 0

Views: 177

Answers (2)

Eugene Naydenov
Eugene Naydenov

Reputation: 7295

Use regular expression like

<div id="res"></div>
<script type="text/javascript">
    var res = document.getElementById('res'),
        re = /\((\d+\.\d+),\s*(\d+\.\d+)\)/,
        str = 'LatLng(41.3371, 19.81717)',
        m = str.match(re);
    res.innerHTML = 'x = ' + m[1] + ' and y = ' + m[2];
</script>

DEMO

Upvotes: 0

epoch
epoch

Reputation: 16615

Using regular expressions you can do /^LatLng\((\d+\.\d+), (\d+\.\d+)\)$/.

With javascript:

console.log('LatLng(41.3371, 19.81717)'.match(/^LatLng\((\d+\.\d+), (\d+\.\d+)\)$/)[1]);​

Upvotes: 2

Related Questions