I have strings which I want to split by either "near", "close", or "around" using JavaScript. What is the correct regex for this?
<script>
var string = "restaurants near seattle";
var string2 = "restaurants close to seattle";
var string3 "restaurants around seattle";
string = string.split('near|close|around');
console.log(string);
</script>
CodePudding user response:
var string = "restaurants near seattle";
var string2 = "restaurants close to seattle";
var string3 = "restaurants around seattle";
const regex = / *(?:near|close|around) */;
console.log(string.split(regex));
// [ 'restaurants', 'seattle' ]
console.log(string2.split(regex));
// [ 'restaurants', 'to seattle' ]
console.log(string3.split(regex));
// [ 'restaurants', 'seattle' ]
CodePudding user response:
use regex there are whitespaces to make sure it doesn't break when there are some words that contains "close" or "near" inside of them
string = string.split(/ near | close | around /);