简体   繁体   中英

How to extract in elegant way the string using the regular expression in JavaScript?

I have the following script which I'm fetching as text: http://pastebin.com/c8XHN27N

How can I cut/extract the desired URL from it using a regular expression?

I need to get the next value from the script above: t="https://s3.amazonaws.com/s3.maketutorial.com/users/7a75f78cb4644e4188ad82d063b1f54b/settings.txt"

Don't know if this is what you want. But this will help you extract all urls from the script file

var src = "...";
var reg = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim
var urls = src.match(reg);
console.log(urls);
/* [
    "http://www.walkme.com/",
    "https://localhost/mt/resources/",
    "https://localhost/mt/lib/maketutorial_lib.js",
    "https://d3b3ehuo35wzeh.cloudfront.net",
    "https://s3.amazonaws.com/s3.maketutorial.com/users/7a75f78cb4644e4188ad82d063b1f54b/settings.txt"
] */

https://regex101.com/r/aD4lW7/1

There are 3 t vars in the script you passed, all with the same value inside, so there is no way to distinguish them.

Then we can pick up the first of the 3 with a simple:

script = "...";
tVar = script.match(/t="[^"]*"/)[0] || '';
console.log(tVar); 
// "t="https://s3.amazonaws.com/s3.maketutorial.com/users/7a75f78cb4644e4188ad82d063b1f54b/settings.txt""

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