Popular posts

Pages

Saturday, September 7, 2013

Regular expression in javascript / jquery

In this small snippet I'm going to show usage regex in javascript (with jquery). I'm not going to explain the usage and importance of regex in programming. There are entire books written solely on regex :). All I can say is regex can be one of the most powerful tools in your coding toolkit.

So here is the situation: I've got a website. A text <input> inside a form and drop-down <select> object. Now based on the change in <select> I want to replace some content in the <input> text value.

HTML
<select>
    <option value="SEV2/min">sev2/min</option>
    <option value="SEV3/maj">sev3/maj</option>
    <option value="SEV4/cri">sev4/cri</option>
</select>
<br>
<input id="sms" type="text" value="bharti, sev: SEV2/min,circle: bihar,impact: voice" />

JS
var re = /sev:\sSEV\d\/[a-zA-Z]+,/;
$("select").on('change',function(){
    var newsev =  $(this).val();
    var text = $("#sms").val();
   
    var newtext = text.replace ( re, "sev: " + newsev + "," );
    $("#sms").val( newtext );
});

Once the <select> is changed, the 'sms' text becomes for ex:

[bharti, sev: SEV4/cri,circle: bihar,impact: voice]

jsfiddle link: here

The html is straight forward. Coming to JS now, here is the sequence:
- define a 're' variable which will be our regular-expression PATTERN
- get the value of <select> drop-down, everytime it is changed
- get the text value of "sms" element.
- populate a variable 'newtext' using the function str.replace( re-pattern, "new string" ). The replace takes two arguments. first, the pattern 're' (or actual string, eg: "sev4"), and second the string to replace matched text. After this call, the 'newtext' contains the updated string.
- set the value of 'sms' element to 'newtext'

This is all about replace(re,"new str") function, hope you enjoyed it!