I have a regex string that matches the specific part of the string that I need as seen here .
/[^\/,\s\?#]+?\.[^\/,\s]+?(?=\/|\s|$|\?|#)/g
I want to use this regex in javascript to strip the parts of a string that do not match the regex and then store the result in a variable. I just cant seem to find any way of doing this!
The only regular expression functions I have found in JS are compile(), exec(), test() and toString(). None of these seem to fit my needs. How can I do this?
Thanks
Use string.match
function to return all the matched characters as array elements.
string.match(/[^\/,\s\?#]+?\.[^\/,\s]+?(?=\/|\s|$|\?|#)/g)
If you want to remove the matched portion then use string.replace
var s = string.replace(/[^\/,\s\?#]+?\.[^\/,\s]+?(?=\/|\s|$|\?|#)/g, "")
The way to do this would be to use the string.match()
function, as seen here on the Mozilla Developer Page .
So, your function call would look like
string.match(/[^\\/,\\s\\?#]+?\\.[^\\/,\\s]+?(?=\\/|\\s|$|\\?|#)/g)
If you plan on stripping away anything that doesn't match, then you could use
string.replace(/[^\\/,\\s\\?#]+?\\.[^\\/,\\s]+?(?=\\/|\\s|$|\\?|#)/g, '')
, as seen here and then store it into another variable.
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.