0

I'm kind of a newby with Javascript, and regex in general and would appreciate all help I can receive!

Consider the following command: [Doesn't matter where it's executed]

/Ban Tom {Breaking The Rules} 5

What I need to do is detect the string between {}, replace the spaces with underscores there(_) and remove the curly brackets around the new string. Example of outcome:

/Ban Tom Breaking_The_Rules 5

Thanks, Tom.

Tom
  • 55
  • 5
  • 1
    It'll help us help you if you post what you've tried (even if you haven't gotten very far---show us your regex). – Andrew Cheong Oct 31 '13 at 07:26
  • As mentioned in the post, I'm quite a nooby regex. I tried a different approach using .split("{") and .split("}") but that didn't get me too far :( – Tom Oct 31 '13 at 07:27
  • 1
    Here's an interactive tutorial: http://regexone.com/. Go through a few pages and come back with what you've gathered might be useful toward your problem. You'll learn a lot more that way! (And the answer will make more sense too :-) Then, we're happy to polish it up for you, iron out any syntax issues, etc. – Andrew Cheong Oct 31 '13 at 07:29

4 Answers4

0

use string.toCharArray() and parse through the array for matching { and spaces to replace them.

Govan
  • 7,751
  • 5
  • 26
  • 42
0

You don't really need a RegEx as this can be achieved by just normal javascript:

<script type="text/javascript">
    var str = "/Ban Tom {Breaking The Rules} 5";
    var oldStr = str.substring(str.indexOf("{"), (str.indexOf("}") + 1));
    var newStr = oldStr.replace(/ /g, "_").replace("{", "").replace("}", "");

    alert(str.replace(oldStr, newStr));
</script>
pazcal
  • 929
  • 5
  • 26
0
var str = '/Ban Tom {Breaking The Rules} 5';  
var patt=new RegExp('{[^}].*}',i);  
var res = patt.exec(str);  

//include res check here.....  
var newStr = res[0].replace(/ /g, '_');  
newStr = newStr.replace(/[{}]/g, '');  
str = newStr.replace(res[0], newStr);
lvil
  • 4,326
  • 9
  • 48
  • 76
0
// The Message:
var foo = "/Ban Tom {Breaking The Rules} 5";

// Replace Whitespace in braces:
foo = foo.replace(/\s+(?=[^\{\}]*\})/g, "_");

//Replace braces with nothing:
foo.replace(/[\{\}]/g,""):

First regex explanation:

\s+        // Match whitespace
(?=        // If followed by:
[^\{\}]*   // Any number of characters except braces
\}         // The closing brace
)          // End of the lookahed

This post provided most of the information, I just adapted it to javascript.

Community
  • 1
  • 1
Kamikai
  • 185
  • 1
  • 6