使用正则表达式进行搜索/替换

时间:2013-05-28 09:47:23

标签: javascript regex

我有一个像item width200height300这样的字符串。宽度和高度的值可以不同。像这样 item width100height100或项width50height300

如何使用正则表达式搜索和替换widthxxxheightxxx

2 个答案:

答案 0 :(得分:3)

像这样:

/width\d+height\d+/

答案 1 :(得分:2)

function replacer(match, p1, p2){
  // do something with p1 or p2
  return "item width"+p1+"heigth"+p2;
};
newString = "item width50height300".replace(/width(\d+)height(\d+)/, replacer);
console.log(newString);

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace