kouts
kouts

Reputation: 360

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

Upvotes: 8

Views: 20361

Answers (6)

ellockie
ellockie

Reputation: 4278

Using Set + Array for this, additionally checking the "" empty string edge case:

const hasOnlyGivenCharType = (str, char) => {
    const chars = Array.from(new Set(str))
    return !chars.some(c => c !== char) && !!chars.length 
}

console.log(hasOnlyGivenCharType('ssssss', 's')) //  -> true
console.log(hasOnlyGivenCharType('sss s', 's'))  //  -> false
console.log(hasOnlyGivenCharType('so', 's'))     //  -> false
console.log(hasOnlyGivenCharType('', 's'))       //  -> false

Upvotes: 0

Jacob
Jacob

Reputation: 1835

Use a RegEx:

const allOne = str => /^(.)\1*$/.test(str)
console.log(allOne(prompt("input")))

Explanation of the RegEx:

^(.)\1*$   full RegEx
^          start of line
 (.)       any character, stored in group 1
    \1*    repeat group 1 zero or more times
       $   end of line

Upvotes: 2

gokublack
gokublack

Reputation: 1470

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

Upvotes: 3

Piotr Misiejuk
Piotr Misiejuk

Reputation: 43

Do it with sssssnake

'sss'.split('s').some(s => s) === true
'sssnake'.split('s').some(s => s) === false

Upvotes: 2

sagar43
sagar43

Reputation: 3464

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/

Upvotes: 7

Amit Joki
Amit Joki

Reputation: 59292

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
}

Upvotes: 4

Related Questions