【问题标题】:jQuery: split string and then insert into input and selectjQuery:拆分字符串,然后插入输入并选择
【发布时间】:2009-10-09 08:41:47
【问题描述】:

我有这样的字符串:

"Car is blue"

字符串也可以是这样的:

"Flower is not at all beautiful"

我有这样的html:

<input class="subject" />
<select class="isornot">
    <option>is</option>
    <option>is not</option>
</select>
<input class="adjective" />

我需要拆分字符串并将其放入表单中的适当位置。对于第一个字符串,主语 val 应该是 car,应该选择 is,形容词值应该是 blue。对于第二个字符串,flower 是主语,is not 是选择选项,'at all beautiful' 应该是形容词。

因此拆分应该是或不是。不知道该怎么做。谢谢。

【问题讨论】:

  • 模式是否总是一个单词,后跟一个空格,后跟一个'is'或'is not'?

标签: javascript jquery html


【解决方案1】:

给你:

var str = "Car is not blue";
var match = str.match(/^(.+?)\s+(is(?:\snot)?)\s+(.+)$/);
if (match) {
    $('input.subject').val(match[1]);
    $('select.isornot').val(match[2]);
    $('input.adjective').val(match[3]);
} else {
    alert("Could not parse message.");
}

参考资料:

【讨论】:

    【解决方案2】:

    添加ID为“字符串”的输入框

    函数拆分() { var strings=$("#string").attr("value").split("is not"); if (strings.length==2){ assingData(字符串,1); } 别的{ strings=$("#string").attr("value").split(" is "); assingData(字符串,0); } } 函数assingData(值,索引){ 如果(值。长度==2){ $(".subject").attr("value",value[0]); $(".isornot option:eq("+index+")").attr("selected", "selected"); $(".形容词").attr("价值",价值[1]); } 别的{ alert("格式错误的字符串"); } }

    【讨论】:

    • assingdata,嘻嘻,非常感谢。这更像是我所设想的,使用拆分而不是正则表达式,这对我来说很重要的原因是因为我的实际用例要复杂一些,而且更容易适应这个解决方案而不是正则表达式。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    相关资源
    最近更新 更多