0

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?

2 Answers 2

3

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).

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

1 Comment

Thank you, simpler than what I thought! I feared I had to use one of those complex lookahead expressions.
0

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.

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.