soeasy123
V2EX  ›  问与答

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

  •  
  •   soeasy123 · Jun 20, 2019 · 2362 views
  •   You need to sign in to view this topic
    This topic created in 2622 days ago, the information mentioned may be changed or developed.

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

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

    要匹配出 value 的值

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

    一条大概做不到..
    auroraccc
        4
    auroraccc  
       Jun 20, 2019
    一定非得正则吗,使用 jsdom 之类的解析然后通过方法查找会不会好一些
    yuuko
        5
    yuuko  
       Jun 20, 2019
    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  
       Jul 3, 2019
    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 ));
    })
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3685 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 00:41 · PVG 08:41 · LAX 17:41 · JFK 20:41
    ♥ Do have faith in what you're doing.