ajax333221
ajax333221

Reputation: 11764

Regex Wild Card question

Code:

strx = "exam/unwanted_tex/ple";
strx = strx.replace(/\/.+\//, '');
alert(strx); // Alerts "example"

2 quick questions:

  1. This code replaces everything within "/" and "/"?
  2. What difference is to use ".*" instead of ".+"

Upvotes: 0

Views: 1368

Answers (3)

Joe Landsman
Joe Landsman

Reputation: 2177

  1. Yes

  2. '*' and '+' are called quantifiers. '*' matches the character or group that precedes it zero or more times. In a sense, this makes the match optional. '+' matches the character or group that precedes one or more times. In your particular example there is no practical difference. However, when used in other applications the distinction is very important. Here is an example:

'*' Quantifier (match zero or more times)

// Match 'y' in Joey zero or more times
strx = "My name is Joe";
strx = strx.replace(/Joey*/, 'Jack');
alert(strx)  // Alerts "My Name is Jack"

'+' Quantifier (match one or more times)

// Match 'y' in Joey one or more times
strx = "My name is Joe";
strx = strx.replace(/Joey+/, 'Jack');
alert(strx)  // Alerts "My Name is Joe"

Upvotes: 1

Jared Ng
Jared Ng

Reputation: 5071

  1. Yes, that is correct
  2. .* means: . match any single character, * zero or more times,

    .+ means: . match any single character, + one or more times

Upvotes: 1

jdc0589
jdc0589

Reputation: 7018

  1. yes
  2. ".*" = any character ANY number of time. ".+" = any character ONE OR MORE times

Upvotes: 0

Related Questions