0

I'm trying to find a way to spilt a string into single words OR phrases where the phrase is enclosed in quotes. For example:

javascript 'sql server' vbscript

would be split into:

  • javascript
  • sql server
  • vbscript

I got help yesterday with this question which splits the string into single words using

/[-\w]+/g

I've been wrestling with the dark art of regular expressions and found this question which does a similar thing in php but even with the explanation it still doesn't make a great deal of sense to me (and doesn't work when I copy/paste into javascript!)

/"(?:\\\\.|[^\\\\"])*"|\S+/

Any help appreciated even a pointer to an easy to understand guide to regular expressions!

Community
  • 1
  • 1
Derek
  • 2,092
  • 1
  • 24
  • 38

3 Answers3

1

You should try the following:

/([-\w]+)|'([^']*)'/g

However, this is will fail if you have any form of single-quotes inside your quoted strings, that means, you cannot escape quotes with this construct.

Daniel Baulig
  • 10,739
  • 6
  • 44
  • 43
1

try this:

var pattern = /('[^']+'|[-\w]+)/g;
var text = "javascript 'sql server' vbscript";
console.log(text.match(pattern));
tarmaq
  • 422
  • 2
  • 7
0

Maybe you could try this var text = ... var split = function(tx) {return tx.split("\'", } This should split it along quotes. Then just use the length to figure it out, as all the even numbered indexes are quotes. Then join the odd indexes and do a split(" ") to get the words

Johm Don
  • 609
  • 2
  • 5
  • 15