JS Regex to match with a space before special character
<p>I am trying to pull out a series of words starting with special characters from a string. My code is:</p>

<pre><code>var specialChars = "!#^@&gt;-/*";
var firstSpecialCharIndex = inputString.search(/[\\!\\#\\^\\@\\&gt;\\\-\\/\\*]/);
var plainText = inputString.substring(0, firstSpecialCharIndex);
var result = {};
result["text"] = plainText;

for (i = firstSpecialCharIndex + 1; i &lt; inputString.length;) {
    var modifiedString = inputString.substring(i);

    var currentChar = inputString.charAt(i - 1);
    if (result[currentChar] == null)
        result[currentChar] = [];
    var text = "";
    var specialCharIndex = modifiedString.search(/[\\!\\#\\^\\@\\&gt;\\\-\\/\\*]/);
    if (specialCharIndex != -1) {
         text = modifiedString.substring(0, specialCharIndex);
        text = text.trim();
        result[currentChar].push(text);
        i += specialCharIndex + 1;
    } else {
        text = modifiedString.substring(0);
        text = text.trim();
        result[currentChar].push(text);
        i = inputString.length;
    }
}
</code></pre>

<p>Now this sort of works, and correctly turns the string:</p>

<pre><code>String start ^a #b #c @d &gt;e *f /g
</code></pre>

<p>into:</p>

<pre><code>{"text":"String start ","^":["a"],"#":["b","c"],"@":["d"],"&gt;":["e"],"*":["f"],"/":["g"]}
</code></pre>

<p>The issue is with using the characters in the original string. Currently, the Regex thinks that <code>string@string</code> should match to <code>@string</code> when it shouldn't. <strong>I want to only match when there is a space before a special character.</strong></p>

<p>Is it possible to require a space before using the Regex? Is there any other way to the Regex should be cleaned up, or is it correct for its purpose? Or would I need to write some more JS to check the values then clean them up or something?</p>

<p>Many thanks</p>