views:

4219

answers:

2

I have strings like this:

"Car is blue"

String could also be like this:

"Flower is not at all beautiful"

I have html like this:

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

I need to split the string and put it into the appropriate places in the form. For the first string, the subject val should be car, is should be selected, and adjective value should be blue. For the second string, flower is the subject, is not is the select option, and 'at all beautiful' should be the adjective.

Therefore the split should be is or is not. Not sure how to go about it. Thanks.

+3  A: 

Here you go:

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.");
}

References:

a paid nerd
+1  A: 

Adding a input box with the ID "string"


function split()
{
 var strings=$("#string").attr("value").split("is not");
 if (strings.length==2){
    assingData(strings,1); 
 }
 else{
    strings=$("#string").attr("value").split(" is ");
    assingData(strings,0);
 }
}

function assingData(value,index){
    if(value.length==2){
     $(".subject").attr("value",value[0]);  
     $(".isornot option:eq("+index+")").attr("selected", "selected");
     $(".adjective").attr("value",value[1]);
    }
    else{
     alert("malformed strings");
    }

}
Kristian Damian
assingdata, heehee, thank you so much. This is more like what I envisioned, using split rather than regex, and the reason why that's important to me is because my real usecase is somewhat more complicated, and it's easier to adapt this solution rather than the regex. Thanks.
Mark