Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check if string contains only certain character

I want to return true if a given string has only a certain character but any number of occurrences of that character.
Examples:

// checking for 's'
'ssssss' -> true
'sss s'  -> false
'so'     -> false
like image 848
kouts Avatar asked Dec 06 '22 23:12

kouts


2 Answers

Check this

<div class="container">
    <form action="javascript:;" method="post" class="form-inline" id="form">
        <input type="text" id="message" class="input-medium" placeholder="Message" value="Hello, world!" />

        <button type="button" class="btn" data-action="insert">Show</button>

    </form>
</div>

JavaScript

   var onloading = (function () {

            $('body').on('click', ':button', function () {
                var a = document.getElementById("message").value;
                var hasS = new RegExp("^[s\s]+$").test(a);
                alert(hasS);
            });

    }());

Example http://jsfiddle.net/kXLv5/40/

like image 73
sagar43 Avatar answered Dec 21 '22 23:12

sagar43


Just check if anything other than space and "s" is there and invert the boolean

var look = "s";
if(!new RegExp("[^\s" + look + "]").test(str)){
   // valid
}

or check if they're the only one which are present with the usage of character class and anchors ^ and $

var look = "s";
if(new RegExp("^[\s" + look + "]$").test(str)){
   // valid
}
like image 21
Amit Joki Avatar answered Dec 22 '22 00:12

Amit Joki