Javascript check if string contains only certain character

15,281

Solution 1

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/

Solution 2

first, convert the string into an array using split,

const letters ='string'.split('')

then, use the Set data structure and pass the array as an argument to the constructer. Set will only have unique values.

const unique = new Set(letters)

this unique will have only the unique characters, so, when you pass sss then this will have only a single s.

finally, if the unique array contains only one element, then we can say this string only contains the same letter.

if (unique.size === 1) { // the string contains only the same letters

Your function should look like this,

function isIdentile(string) {
    const letters = string.split('');
    const unique = new Set(letters)
    
    return unique.size === 1 ? true: false;
}

Solution 3

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
}

Solution 4

Do it with sssssnake

'sss'.split('s').some(s => s) === true
'sssnake'.split('s').some(s => s) === false
Share:
15,281

Related videos on Youtube

kouts
Author by

kouts

Updated on September 16, 2022

Comments

  • kouts
    kouts over 1 year

    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
    
  • Cmdd
    Cmdd over 2 years
    there is a small error: size it's a Set property, not a function. I'll edit it :-)