简体   繁体   中英

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?

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]);​

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM