9

I am trying to replace a spaces within a string with hypen.

For example

'this is a sample'

should be

'this-is-a-sample'

.replace('/\s+/g', '-') gives an error

Invalid string literal '/\s+/g'. Illegal character sequence '\s' in string literal.

1
  • I think that's pretty close, except one doesn't need to use forwardslash / delimiters... and backslashes may be escaped. So more like this: .replaceAll('\\s+', '-') Commented Apr 13, 2015 at 13:57

3 Answers 3

7

\ is always an escape character.

  • To use the regex \s, you need to use \\s.
  • To use a literal \, use \\\\.
8

why don't you use the replace method and pass in space (' ') & hyphen (-) as parameters. it will replace each space in the string with a hyphen as you expect.

string test = 'this is a space';
string newtest = test.replace(' ','-');
system.debug(newtest);

quick try in dev console anonymous window with debug log

enter image description here

1
  • 1
    This only works "as expected" if they only mean to remove "space" (0x20), and not other forms of whitespace, like tab (0x09), line feed (0x0a), and carriage return (0x0d).
    – sfdcfox
    Commented Apr 13, 2015 at 14:01
1

If you want to remove white space you can use this

string test = 'this is a space';
string newtest = test.replaceAll('\\s+','-');
system.debug(newtest);

Otherwise you wont have to use a regular expression. Use simply use this code:

string test = 'this is a space';
string newtest = test.replace(' ','-');
system.debug(newtest);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .