RegEx matching space not starting/ending with char

I need to split the text to the words but I also need to ignore the & character. That means for example the word "h & m" has stay together. Regex must also work in JavaScript and node.js.

I used /(?!&)\s(?!&)/g. But that ignore space with & character only at end.

Answers


If you cannot split (and you cannot split since there is no look-behind in JS), you need to match:

\S+(?:\s&\s\S+)*

See demo

Code:

var re = /(\S+(?:\s&\s\S+)*)/g; 
var str = 'H & M shopping mall';
var m = str.match(re);
document.getElementById("res").innerHTML = m;
<div id="res"/>

You can use look ahead and look behind... (just add < to your current regex)

/(?<!&)\s(?!&)/g
   ^

See DEMO

Explanation:

  • All spaces whose previous character is not &.. (?<!&) and next character is also not &.. (?!&)

Need Your Help

Line breaks in Jade/Mongo output

javascript node.js mongodb pug

I've read all the questions here on stackoverflow regarding this matter, but none has satisfied my needs.