AlreadyLost
AlreadyLost

Reputation: 827

regex javascript to look for a string with start and end pattern

I would appreciate if someone can help me to come up with a regex that I can look for a pattern in a href. Pattern is to look for a query string hint=value& and then replace it with a new value hint=value2&. so the pattern should start with hint and end with & if there are more query strings or end of the value for hint.

I dont want to use jquery external library (purl). Any help will be much appreciated.

Upvotes: 2

Views: 1025

Answers (2)

Manish Waran
Manish Waran

Reputation: 92

Snippet:

function replaceValue(newValue, url) {
    const regex = /\?.*?&((hint)=(.*)?&(.*))/g;
    const matches = regex.exec(url);
    let result = '';
    matches.forEach((matchString , index) => {
        if(index === 3) {
            result += newValue;
        }
        else {
            result += matchString;
        }
    });
    return result;
}

This would help you

Upvotes: 0

vallentin
vallentin

Reputation: 26157

You could use a positive lookahead and check for & or the end of the string.

hint=(.*?)(?=&|$)

Live preview

Since we're using a lookahead, this means that the replacement doesn't need to include the & at the end. Which might be an important factor if hint=value were to be the last query element.

Which in JavaScript would look like this:

const str = "https://www.sample.com/signup?es=click&hint=m%2A%2A%2A%2A%2A%2A%2Ai%40gmail.com&ru=%2F%22";

const replacement = "hint=newstring";

const regex = /hint=(.*?)(?=&|$)/g;

const result = str.replace(regex, replacement);

console.log(result);

Given your example url, then console.log(result) would output:

https://www.sample.com/signup?es=click&hint=newstring&ru=%2F%22

Upvotes: 2

Related Questions