简体   繁体   中英

Is there a function which can match wildcard and replace with string - javascript

I am Developing a project using javascript, php. I need to match wildcard string using javascript like

//users need to enter some url in textbox like strings_1 or strings_2
var strings_1='http://google.com/search?q=Hello World&o=test';
var strings_2='http://google.com/?q=Hello world&o=test';

var search_reg='*//google.com/search?q=*&o=*';
// match each url string_1 and 2 with search_reg, if any string match it should replace * by $1, $2, $3
var final_url_should_be='$1//otherengine/test?q=$2&o=$3';

so final url should be http://otherengine/test?q=Hello World&o=test

Using regex

 //users need to enter some url in textbox like strings_1 or strings_2 var strings_1 = 'http://google.com/search?q=Hello World&o=test'; var strings_2 = 'http://google.com/?q=Hello world&o=test'; var search_reg = '*//google.com/search?q=*&o=*'; // match each url string_1 and 2 with search_reg, if any string match it should replace * by $1, $2, $3 var final_url_should_be = '$1//otherengine/test?q=$2&o=$3'; console.log(replaceUrl(strings_1)); console.log(replaceUrl(strings_2)); function replaceUrl(inputUrl) { return inputUrl.replace(/\bsearch/,'').replace(/\bgoogle.com\//, 'otherengine/test'); }

But if you know the exact words in url(like google.com) which should be replaced, then plain replace() will work, without any regex.

 //users need to enter some url in textbox like strings_1 or strings_2 var strings_1 = 'http://google.com/search?q=Hello World&o=test'; var strings_2 = 'http://google.com/?q=Hello world&o=test'; var search_reg = '*//google.com/search?q=*&o=*'; // match each url string_1 and 2 with search_reg, if any string match it should replace * by $1, $2, $3 var final_url_should_be = '$1//otherengine/test?q=$2&o=$3'; console.log(replaceUrl(strings_1)); console.log(replaceUrl(strings_2)); function replaceUrl(inputUrl) { return inputUrl.replace('search', '').replace('google.com/', 'otherengine/test'); }

If you're just swapping the domains, you can do it this way as well:

/(?<domain>https?:\/\/.*[.][a-zA-Z0-9]{3}\/)(?<path>.*\?.*[=].*)/

You can access the named capture group in regex, and use interpolation to get your results

 var strings_1='http://google.com/search?q=Hello World&o=test'; var strings_2='http://google.com/?q=Hello world&o=test'; var newDomain="https://newdomain.com/"; const replace1 = strings_1.replace( /(?<domain>https?:\/\/.*[.][a-zA-Z0-9]{3}\/)(?<path>.*\?.*[=].*)/, `${newDomain}$<path>`); console.log(replace1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM