1

I want to add a string {something} to a string if it contains href=" or href='.

Note - There could be space around the =.

So, if my input is <a href="http://google.com">Click</a>

The output should be <a href="{something}http://google.com">Click</a>

So far, I have this regular expression which matches with what I want to match, but don't know how to add the string after the matching part.

/href\s*=\s*(\"|\')/

I checked need help with regex in javascript to replace string pattern

1
  • Why don't you use the DOM to do this? Commented Feb 11, 2013 at 9:30

1 Answer 1

3

General answer, following off of your attempt:

string.replace(/href\s*=\s*(\"|\')/, "href=$1{something}");

(The $1 simply references the captured group, whatever matched your parenthesized expression in your regex)

Correct way to modify an element's href:

element.href = '{something}' + element.href;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, and in my case, I wanted to preserve all the spaces, so this is what I followed - string.replace(/(href\s*=\s*[\"|\']\s*)/,"$1{something}"); For beginners - I am using capturing group - The entire pattern inside the first bracket is captured as $1 - href\s*=\s*[\"|\']\s* and I add {something} after it.
and btw, I am not modifying an anchor tag in the dom. I am modifying the text of an input field. The anchor tag appears in the content. Not sure if DOM manipulation using element.href will work here.
@Sandeepan You can't replace the parentheses with square brackets around the quotation marks like that—that causes all the characters inside the square brackets to match literally, including the pipe (|). You can instead do this /(href\s*=\s*["']\s*)/, which will match one of the characters in the 'character set', in this case one of the quote marks

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.