Raisen
Raisen

Reputation: 4495

Replace multiple identical characters with a string

Using Javascript, I want to replace:

This is a test, please complete ____.

with:

This is a test, please complete %word%.

The number of underlines isn't consistent, so I cannot just use something like str.replace('_____', '%word%').

I've tried str.replace(/(_)*/g, '%word%') but it didn't work. Any suggestions?

Upvotes: 0

Views: 64

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521389

I'm going to suggest a slightly different approach to this. Instead of maintaining the sentence as you currently have it, instead maintain something like this:

This is the {$1} test, please complete {$2}.

When you want to render this sentence, use a regex replacement to replace the placeholders with underscores:

var sentence = "This is the {$1} test, please complete {$2}.";
var show = sentence.replace(/\{\$\d+\}/g, "____");
console.log(show);

When you want to replace a given placeholder, you may also use a targeted regex replacement. For example, to target the first placeholder you could use:

var sentence = "This is the {$1} test, please complete {$2}.";
var show = sentence.replace(/\{\$1\}/g, "first");
console.log(show);

This is a fairly robust and scalable solution, and is more accurate than just doing a single blanket replacement of all underscores.

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370789

Remove the capturing group, and make sure _ repeats with + (at least one occurrence, matches as many _s as possible):

const str = 'This is a test, please complete ____.';
console.log(
  str.replace(/_+/g, '%word%')
);

The regular expression

/(_)*/

means, in plain language: match zero or more underscores, which of course isn't what you're looking for. That will match every position in the string (except positions in the string between underscores).

Upvotes: 3

Related Questions