JavaScript > Regular Expressions Modifiers

Match not followed by particular character in JavaScript

How to match any string that is not followed by a particular character in a specific string in JavaScript?


By using ?! quantifier we can match any string that is not followed by a particular character in a specific string.

EXAMPLE: 'Ear' is not followed by 'rings'.

<p>Click the below button to match a string .</p>
<input type="button" onclick="mySearch()" value="Search">
<p id="myId"></p>

<script>
    function mySearch() {
        var a = "Last yEar is all were wEar rings to their right Ear?"
        var b = /ear(?! rings)/gi;
        var r = a.match(b);
        document.getElementById("myId").innerHTML = r;
    }
</script>

In the above code snippet we have given Id as "myId"to the second <p> element in the HTML code. There is a function mySearch() in the<script>block which is connected to the onclick of the HTML button and there is a string with value "Last yEar is all were wEar rings to their right Ear? " to the variable a, we can find the the word "Ear" in 3 places (yEar, wEar, Ear) in a string. But we need to match 'Ear' not followed by a 'rings' in a string, for that we are using ?! quantifier in the variable bvar b = /ear(?= rings)/g in this ?! quantifier searches in a string where 'Ear' is not followed by 'rings' with the help of a global, case insensitive search gi. Variable returns the global, case insensitive search result. Onclick of the button "Search" in HTML code fires the function mySearch() in the <script> block at the same time ?! quantifier do the global, case insensitive search for the word 'Ear' not followed by 'rings' in a string and returns 'Ear' from the words 'yEar & Ear' as a output.

OUTPUT

NOTE: The output is returning the 'Ear' from the words "yEar & Ear". It is not returning the 'Ear' from word "wEar", because it is followed by the "rings".

 Views: 3248 | Post Order: 152



Write for us






Hosting Recommendations