简体   繁体   中英

Regex to find some pattern in javascript

I have a string which contains some pattern of text, and I need to find that pattern.

For Example:

var texttochange = ' [variable field="##Menu.name##" /]<br>
                     [img value='##Menu.image##' width='200' height='200'
                     borderthickness='0' keepaspect='0' bordercolor='#'
                     alttext='' borderstyle='solid'][/img]<br>
                     [variable field="##Menu.description##" /]<br>
                     [variable field="##Menu.cost##" /]<br>';

And I wrote the below regex to find this pattern ##sometext.sometext##

var regexp = /##\S+.\S+##/gi;
var matchesfound = regexp.exec(texttochange);

According to my requirement I need all the fields ie ["##Menu.name##"],["##Menu.image##"],["##Menu.description##"],["##Menu.cost##"] But in the var matchesfound , I am only getting ["##Menu.name##"]

Try this:

var str = ' [variable field="##Menu.name##" /]<br>
            [img value="##Menu.image##" width="200" height="200" 
            borderthickness="0" keepaspect="0" bordercolor="#" 
            alttext="" borderstyle="solid"][/img]<br>
            [variable field="##Menu.description##" /]<br>
            [variable field="##Menu.cost##" /]<br>';

var regex = /##\S+.\S+##/gi, result, indices = [];

while ( (result = regex.exec(str)) ) {
  indices.push(result.toString());
}
console.log(indices);

Working Demo

var texttochange = '[variable field="##Menu.name##" /]<br>[img value="##Menu.image##" width="200" height="200" borderthickness="0" keepaspect="0" bordercolor="#" alttext="" borderstyle="solid"][/img]<br>[variable field="##Menu.description##" /]<br>[variable field="##Menu.cost##" /]<br>'

var regexp = /##\S+.\S+##/gi;


texttochange.match(regexp)
["##Menu.name##", "##Menu.image##", "##Menu.description##", "##Menu.cost##"]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM