1

what does this mean?

name = name. replace(/([A-Z]) /g, " -$1" );

it's js.

correction i meant name = name.replace(/([A-Z]) /g, "-$1" );

1
  • 1
    is that JavaScript? Regex can be formatted differently depending on what programming language you're representing it in. Commented Nov 8, 2010 at 16:02

3 Answers 3

2

It means:

Take the string "name," and look for each uppercase letter followed by a space. When you find one occurrence, replace it with a hyphen, then the letter. Once you've done that for all occurrences, assign this new string back to the "name" variable.

For example, if "name" is AB CD before this line is executed, "name" will be A-BCD after this line is executed.

Sign up to request clarification or add additional context in comments.

5 Comments

I'm pretty sure the /g means it's just at the end of the string, no? I tested this real quick in javascript and: "HEllo MY friends" was replaced with "HEllo M -Y friends".
@Matt: It looks for each uppercase letter followed by a space, and the space is removed.
Javascript may not recognise the /g flag. If it's something like Perl then /g means global.
I screwed up the regex. There's a space in the parens after the [A-Z]. The g means "global" in PERL. So the pattern is looking for capital letters that are followed by a space.
@Gazillion: No. The g at the ends means it's "gobal", thus it's repeated for all occurrences of the expression instead of only the first.
1

Very briefly, the [A-Z] means match any upper-case letter, the /g bit means do it globally (the entire input string), and the -$1 bit means replace each matching group X with -X. $1 refers to the bit in parenthesis in the first argument.

So, if the input is "HE LLO" you'll get "H-E LLO" out. If the input is "He LL o" you should get "He L-L o" out.

I'd recommend you read up on regular expressions since they can be very complex.

2 Comments

What do you mean by? $1 refers to the bit in parenthesis in the first argument.
$1 is what's called a "backreference". Each pair of parenthesis defines a backreference that can be later referred to by the $n syntax. The first backreference is $1, the second is $2 and so on. So the "replace" part of the expression refers to the first backreference in the regex.
0

After (A-Z) is a space. So it should only match uppercase characters followed by a space. Those are replaced by " -" and the original character (backreference). So for the string "HELLO MY Friends" the result would be HELL -OM -YFriends. the /g means global, so replace all occurences.

Tried it in perl:

$var = "HELLO MY Friends";
$var =´ s/([A-Z]) / -$1/g;
print $var . "\n";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.