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