I perform a test if a string contains a substring, if yes, I would like to have the substring that not matched
var string = "Hello world";
var toMatch = new RegExp('world', 'i');
if (string.match(toMatch)){
// should return "Hello "
}
Just use replace()
:
var string = "Hello world";
var toMatch = new RegExp('world', 'i');
var newString=string.replace(string.match(toMatch),"");
If you want to return, use
return string.replace(string.match(toMatch),"");
It will give you a string without "world" if it contained "world" and unmodified string if there was no "world"
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.