如何提取onChange方法's使用Regex的字符串参数

How to extract onChange method's String parameters using Regex?

本文关键字:使用 Regex 参数 字符串 何提取 提取 方法 onChange      更新时间:2023-09-26

我有如下所示的select元素

<select name="selectid1" id="selectid1" onChange="script.selectChange(this,'tr');">.......</select>

<select name="selectid2" id="selectid2" onChange="script.selectChange(this,'div');">.......</select>

我想使用正则表达式提取两个select元素的onChange属性的selectChange方法的String参数(第二个参数(trdiv

我可以使用获得onChange的值

var selectid1 = $('#selectid1').attr('onChange'); //script.selectChange(this,'tr');

var selectid2 = $('#selectid2').attr('onChange'); //script.selectChange(this,'div');

我应该使用什么正则表达式才能从变量中获得字符串'tr''div'

如果只是针对测试用例,请使用以下方法和String.match函数:

var selectid1 = "script.selectChange(this,'tr')",
    param = selectid1.match(/,'s?['"]([^)]+)['"]/)[1];
console.log(param);  // tr
/onChange="script.selectChange'(this,'([^']*)'/g

此处演示-->https://regex101.com/r/uW2aQ6/1