I am trying to create a regular expression in JS which will match the occurences of box
and return the full compound word
Using the string:
the box which is contained within a box-wrap has a box-button
I would like to get:
[box, box-wrap, box-button]
Is this possible to match these words only using the string box
?
This is what I have tried so far but it does not return the results I desire.
var str ='the box which is contained within a box-wrap has a box-button';
var regex = new RegExp('([\w-]*box[\w-]*)', 'g');
document.getElementById('output').innerHTML=str.match(regex);
Try this way:
([\w-]*box[\w-]*)
Requested by comments, here is a working example in javascript:
function my_search(word, sentence) { var pattern = new RegExp("([\\\\w-]*" + word + "[\\\\w-]*)", "gi"); sentence.replace(pattern, function(match) { document.write(match + "<br>"); // here you can do what do you want return match; }); }; var phrase = "the box which is contained within a box-wrap " + "has a box-button. it is inbox..."; my_search("box", phrase);
Hope it helps.
我将它扔在那里:
(box[\w-]*)+
This should work, note the 'W' is upper case.
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
\\Wbox\\W
It looks like you're wanting to use the match with a regex. Match is a string method that will take a regex as an argument and return an array containing matches.
var str = "your string that contains all of the words you're looking for";
var regex = /you(\S)*(?=\s)/g;
var returnedArray = str.match(regex);
//console.log(returnedArray) returns ['you', 'you\'re']
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.