I have a string like this
var str = "WebApi served the request: /api/user/v1 in : 249ms with status : OK";
I need to extract /api/user/v1
from str. How do I do it in Javascript?
I have also tried using some regular expressions as shown below. This method works fine, but is there any better way to do it?
var str = "WebApi served the request: /api/user/v1 in : 249ms with status : OK"; var patt1 = /\\/.*in/; //Extract until the word "in" var result1 = str.match(patt1); var patt2 = /[^\\s]+/; //Extract the 1st string until it reaches a space var result2 = result1[0].match(patt2); console.log(result2);
Match a slash, followed by non-space characters, until lookahead matches a space followed by in
:
var str = "WebApi served the request: /api/user/v1 in : 249ms with status : OK"; const match = str.match(/\\/\\S+(?= in\\b)/); console.log(match[0]);
To check that the string starts with WebApi served the request:
, add that to the start of the pattern and use a capturing group around the /api
part:
var str = "WebApi served the request: /api/user/v1 in : 249ms with status : OK"; const match = str.match(/^WebApi served the request: (\\/\\S+) in\\b/); if (match) { console.log(match[1]); }
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.