V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
soeasy123
V2EX  ›  问与答

一个关于正则匹配 input 值的问题

  •  
  •   soeasy123 · 2019-06-20 16:26:15 +08:00 · 1283 次点击
    这是一个创建于 1764 天前的主题,其中的信息可能已经有所发展或是发生改变。

    input 里的 attribute 位置会变动要怎么匹配 name 为特定值的 value 啊??

    如 <input name="test" type="text" value="123"> <input name="test" type="text" value="456">

    要匹配出 value 的值

    6 条回复    2019-07-03 10:42:47 +08:00
    noqwerty
        1
    noqwerty  
       2019-06-20 16:35:40 +08:00 via Android
    如果一定要用正则的话,可以先 match name=test 再提取 value 的值,也可以写两个规则分别匹配 name 在前和 name 在后的情况
    kkkkkrua
        2
    kkkkkrua  
       2019-06-20 17:15:28 +08:00
    var res =/<input.*name=\"test\"?.*value=\"(?<value>.*)\">/ig.exec('<input name="test" type="text" value="123">');
    console.log(res.groups.value);
    SakuraKuma
        3
    SakuraKuma  
       2019-06-20 17:46:48 +08:00
    先用<input .*>match 出来两个 input.
    再用 /(?<key>[^=])="(?<value>[^"])"/依次 exec 出 key/value pair.

    一条大概做不到..
    auroraccc
        4
    auroraccc  
       2019-06-20 18:54:31 +08:00
    一定非得正则吗,使用 jsdom 之类的解析然后通过方法查找会不会好一些
    yuuko
        5
    yuuko  
       2019-06-20 21:38:38 +08:00
    var s = ['<input name="test" type="text" value="123">', '<input type="text" value="456" name="test">']
    var p = /<input\s.*?((name="test".*?value=("|')([^\3]*)\3)|(value=("|')([^\6]*)\6.*?name="test")).*?>/

    s.forEach(s => {
    var g = s.match(p)
    console.log(g[4] || g[7]);
    })

    一条正则来了
    nnnToTnnn
        6
    nnnToTnnn  
       2019-07-03 10:42:47 +08:00
    let inputStr = ['<input name="test" type="text" value="123">', '<input type="text" value="456" name="test">']

    inputStr .forEach(value => {
    const matchStr = value .match( /<input .*?(\s*value\s*=\s*".*?")/g)[0].replace('<input','').match(/[a-zA-Z]+\s*=\s*".*?"/g)
    let param = {}
    matchStr .forEach((element)=>{
    const key = element.split('=')[0]
    const value = element.split('=')[1]
    param[key ] = value
    })
    console.log( JSON.stringify(param ));
    })
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1125 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:03 · PVG 07:03 · LAX 16:03 · JFK 19:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.