This question already has answers here:
Check for repeated characters in a string Javascript
(14 answers)
Closed 7 years ago.
I need to check if a word is Isogram, the meaning of Isogram, is that a word has no repeating letters.
I need to implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
Here is a test case
isIsogram( "Dermatoglyphics" ) == true
isIsogram( "aba" ) == false
isIsogram( "moOse" ) == false // -- ignore letter case
I am thinking on do this with a Regex.
function isIsogram(str){
//...
}
can you help?
as simple as that
function isIsogram (str) {
return !/(\w).*\1/i.test(str);
}
This will do:
function isIsogram (str) {
return !/(.).*\1/.test(str);
}
You can use it like this by converting the input to a lower case:
var re = /^(?:([a-z])(?!.*\1))*$/;
function isIsogram(str) {
return re.test( str.toLowerCase() );
}
Testing:
isIsogram("Dermatoglyphics")
true
re.test("aba")
false
isIsogram("moOse")
false
Related
This question already has answers here:
Finding uppercase characters within a string
(6 answers)
How to pick only Capital characters from the string?
(5 answers)
Extract only Capital letters from a string - javascript [duplicate]
(4 answers)
Closed 8 months ago.
I've read countless articles about people able to detect if all characters in a string are uppercase...
function isUpperCase(str) {
return str === str.toUpperCase();
}
isUpperCase("hello"); // false
isUpperCase("Hello"); // false
isUpperCase("HELLO"); // true
But I'm curious how I can take a string, and search to see if any characters are uppercase, and if so, return true or return a string with the characters that are uppercase.
Any help is massively appreciated, I'm trying to avoid posts on here but I couldn't find an answer that worked for me anywhere else.
You can use the same logic you used for all uppercase, turn the string to lowercase and if its not equal to the original string it has an uppercase letter in it.
function hasUpperCase(str) {
return str !== str.toLowerCase();
}
console.log(hasUpperCase("hello")); // false
console.log(hasUpperCase("Hello")); // true
console.log(hasUpperCase("HELLO")); // true
You can use a regular expression to filter out and return uppercase characters. However, note that the naïve solution (as proposed by some of the other answers), /[A-Z]/, would detect only 26 uppercase Latin letters.
Here is a Unicode-aware regex solution:
const isAnyUpper = string => /\p{Lu}/u.test(string)
isAnyUpper('a') // false
isAnyUpper('A') // true
isAnyUpper('ф') // false
isAnyUpper('á') // false
isAnyUpper('Á') // true
Assuming the function is only taking string of ascii letters:
function isAllUpper(str) {
return str.split('').findIndex(ch => {
const code = ch.charCodeAt(0);
return code >= 65 && code <= 90;
}) === -1;
}
If you want to return just the string with only the uppercase letters, then you can extend the above slightly:
function onlyUpper(str) {
return str.split('').filter(ch => {
const code = ch.charCodeAt(0);
return code >= 65 && code <= 90;
}).join('');
}
It's as simple as:
const hasUpperCase = str => /[A-Z]/.test(str);
console.log(hasUpperCase('abcd'));
console.log(hasUpperCase('abcD'));
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Using Javascript is there a way to remove extra occurrences of a specific letter in a string?
For example:
remove_extra('a', 'caaaat')
//=> 'cat'
I know there must be a brute force way to do something like this but is there an elegant way? I'm not sure how to approach this algorithm.
you can do this with regex:
var test = "aaabbbccc";
console.log(test.replace(/(.)(?=.*\1)/g, "")); //would print abc
var test2 = "caaaaat";
console.log(test2.replace(/(.)(?=.*\1)/g, "")); //would print cat
Sorry, I misunderstood your question.
To only keep one instance of specified char:
function onlyOneCharOf(string, pattern) {
let first = true;
//if (pattern.length !==1) throw Error("Expected one character");
pattern=pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); //escape RegEx special chars
return string.replace(new RegExp(pattern, "g"), value => {
if (first) {
first = false;
return value;
}
return "";
});
}
console.log(onlyOneCharOf("zzzzzaaabbbbcccc", "a"));
Note: the pattern given to the function is used to create a RegEx. Since some characters are special characters, those characters must be escaped. I updated the function to do that for you. You might also want to check the length, but the length might be larger than 1 for some unicode code points.
If you only want any character to appear once, you can use a Set:
function unique(string) {
return Array.from(new Set(string.split(''))).join('');
}
console.log(unique("caaaat"));
A value in a Set may only occur once.
You can use Array.from to explode a string:
Array.from('caaaat');
//=> ["c", "a", "a", "a", "a", "t"]
You can then use Array#filter to keep everything that is neither "a" nor the first occurrence of "a":
Array.from('caaaat').filter((x, i, xs) => x !== 'a' || xs.indexOf(x) === i).join('');
//=> "cat"
(I leave it to you as an exercise to put this into a reusable function.)
Just be aware that if you choose to interpret char as a regular expression without validating it first, you may have unexpected results:
function onlyOneCharOf(string, char) {
let first = true;
return string.replace(new RegExp(char, "g"), value => {
if (first) {
first = false;
return value;
}
return "";
});
}
onlyOneCharOf('caaat', '.');
//=> "c"
onlyOneCharOf('caaat', '?');
//=> SyntaxError
This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
Closed 4 years ago.
I want to use regex to replace the lowercase letter of every word within a string of words, with an uppercase, ie change it to title case such that str_val="This is the best sauce ever"
becomes "This Is The Best Sauce Ever".
Here is my code
function (str_val) {
let reg_exp = /\s\w/g;
let str_len = str_val.split(' ').length;
while (str_len){
str_val[x].replace(reg_exp, reg_exp.toUpperCase());
x++;
str_len--;
}
return str_val;
}
How do I solve this with regex?
Use below function for title case
function title(str) {
return str.replace(/(?:^|\s)\w/g, function(match) {
return match.toUpperCase();
});
}
This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
Closed 6 years ago.
I'm not sure if I did this right, as I am pretty new to JavaScript.
But I want to lowercase any random string text and then capitalize the first letter of each word in that text.
<script>
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function lowerCase(string) {
return string.toLowerCase();
}
</script>
Just change the method to
function capitalizeFirstLetter(string)
{
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
.toLowerCase() is appended to the last method call.
This method will make the first character uppercase and convert rest of the string to lowercase. You won't need the second method.
A small sample:
function firstLetter(s) {
return s.replace(/^.{1}/g, s[0].toUpperCase());
}
firstLetter('hello'); // Hello
This question already has answers here:
How to check if a string "StartsWith" another string?
(18 answers)
Remove characters from a string [duplicate]
(6 answers)
Closed 9 years ago.
I have an array with multiple entries. Some of these contain # at the beginning. That's an example of an array:
some string
#another string
#one more string
the best string
string with email#mail.com
For validation and grouping I use this part of code (it checked only # for now)
if(linesArray[i] === '#'){
$('#test').append('<li class="string_with_at">'+linesArray[i]+'</li>');
}else{
$('#test').append('<li class="string_no_at">'+linesArray[i]+'</li>');
}
My questions are:
How can I check the # in line start for first group?
How can I remove this symbol from result ('li'+linesArray+'/li') - a may to leave only class to understand that it was an #
How about that:
if(linesArray[i][0] === '#') { //checking the first symbol
//remove first element from result
$('#test').append('<li class="string_with_at">'+linesArray[i].substring(1)+'</li>');
}
else {
$('#test').append('<li class="string_no_at">'+linesArray[i]+'</li>');
}
Function to remove '#' if at position 0, and return newly formatted string:
removeAt = function(s){
if(s.charAt(0) == '#')
return s.substring(1);
return s;
}
This should do the trick:
function addElement (val) {
var match = val.match(/^(#)(.*)/),
at = match[1],
str = match[2],
li = $('<li/>').html(str)
li.addClass('string_' + (at ? 'with' : 'no') + '_at');
$('#test').append(li);
}
linesArray.forEach(addElement);