1

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.

1
  • 1
    Is the pattern always a single word followed by a space followed by a 'is' or 'is not' ? Commented Oct 9, 2009 at 0:10

2 Answers 2

5

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:

Sign up to request clarification or add additional context in comments.

Comments

2

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

}

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.