0
$(this).val().replace(/^\s+|\s+$/g, '');  

a = a.replace(/^-+|-+$/g, '');  

a = a.replace(/[^\w-]/g, '-');  

a = a.replace(/--+/g, '-');   

What these statements exactly do ??

I am not getting what these are doing even read about regular expressions,can any one explain me in detail....

2 Answers2

0
  • /^\s+|\s+$/g: matches whitespace at the beginning or end of a string (replaces with empty string)
  • /^-+|-+$/g: matches hyphens at the beginning or end of a string (replaces with empty string)
  • /[^\w-]/g: matches alphanumeric, _, and - characters (and replaces with a -)
  • /--+/g: matches 2+ - in a row (and replaces with a single -)
Sam
  • 18,756
  • 2
  • 40
  • 65
0

Here is an explanation for each of the terms:

$(this).val().replace(/^\s+|\s+$/g, '');

This replaces any leading spaces or trailing spaces with blanks:

"    Hello" -> "Hello"
"Hello    " -> "Hello"
"  Hello  " -> "Hello"

a = a.replace(/^-+|-+$/g, '');

This replaces any leading - (1 or more times) or trailing - (1 or more times) with blanks.

"Hello----" -> "Hello"
"--- Hello ---" -> " Hello "
"-H-E-L-L-O-" -> "H-E-L-L-O"

a = a.replace(/[^\w-]/g, '-');

This replaces any character that is not (^) a word character (in JavaScript, it is defined to include lowercase and uppercase English alphabets, digits 0 to 9 and underscores), or not a '-' with '-'.

"    Hello" -> "----Hello"
"Hello@@@@" -> "Hello----"
"Hello--123___" -> "Hello--123___"
"@£"$%"!$" -> ""

a = a.replace(/--+/g, '-');

This replaces 2 or more consecutive - with a single '-'.

"--" -> "-"
"Hello--" -> "Hello-"
"------Hello---------" -> "-Hello-"
"H--ello---------" -> "H-ello-"
nhahtdh
  • 52,949
  • 15
  • 113
  • 149
Dominic Zukiewicz
  • 7,704
  • 7
  • 37
  • 57
  • The last one is wrong. It replaces consecutive `-` with single `-`. And the 3rd one is also wrong, `\w` doesn't allow spaces. The 2nd one "-H-E-L-L-O-" example is wrong. – nhahtdh Oct 09 '14 at 10:17
  • Thanks for spotting it, I've corrected it now – Dominic Zukiewicz Oct 09 '14 at 11:14
  • Please run the examples through the console next time. There are still errors after you edited your post, so I edit to correct them. – nhahtdh Oct 09 '14 at 16:51