jQuery Data Type How to - Tokenize string with space seperated values unless values are wrapped in single quotes








Question

We would like to know how to tokenize string with space seperated values unless values are wrapped in single quotes.

Answer


<!DOCTYPE html>
<html>
<body>
  <pre id=res></pre>
    <script>
        var s = "0 asdf asdf asdf 'node name' 2 asdf 45 12";
        var arr = [];
        s.split("'").forEach(function(v,i){
            arr = arr.concat(i%2 ? v : v.trim().split(' '))
        });<!--from w w w.  j  ava  2  s .  c o  m-->
        document.getElementById('res').innerHTML = JSON.stringify(arr);
    
    </script>

</body>
</html>

The code above is rendered as follows: