2

How can I convert this into an one-liner JavaScript regex?

html.replace(/src="(.*?)"/gi, function($1)
{  return $1.replace(/(abc.*?)\/abc/gi, "abc");
});

The above code block should be self-explanatory of what I'm trying to accomplish, but I'll elaborate.

What I'm trying to accomplish is replace all matches of this regex /src="(.*?)"/ which contains the substring: abc[random_characters]/abc to just abc. And so for example

src="abc[random_characters]/abc[random_characters]" => src="abc[random_characters]"

Edit: One-liner without the anonymous function call or callback.

Edit: Solution

html.replace(/src="abc(?:.*?)\/(abc[^"]+)"/gi, "src=\"$1\"");
5
  • 2
    html.replace(/src="(.*?)"/gi, function($1) { return $1.replace(/(abc.*?)\/abc/gi, "abc");}); ha ha -- 1 line, just got rid of the carriage returns. Commented Dec 12, 2014 at 23:34
  • 3
    Your requirements are unclear, please add concret examples of original strings and expected results. Commented Dec 12, 2014 at 23:55
  • Maybe I should be clear on it. I should of have said one-liner without the function call or callback. Commented Dec 13, 2014 at 3:59
  • Note that the solutions below won't work if src doesn't start with abc. Are you sure it is what you want? Commented Dec 13, 2014 at 4:41
  • abc was just arbitrary. Commented Dec 14, 2014 at 9:24

1 Answer 1

2

Use backreference:

html.replace(/src="(abc[^\/]*\/?)+"/gi, 'src="$1"');
  • (abc[^\/]*\/?) — matches abc + random characters (except for /);

  • "$1" — a backreference to the captured group.

However, I'm not quite sure it satisfies you requirements. Your description of a problem is a little bit inconsistent.

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

2 Comments

Somewhat satisfied my requirement, but anyway I figured out already.
I posted it 2 days ago ;) Anyway, I'm glad you got it running.

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.