javascript regex does not work for sentence string - javascript

I am writing a function which takes string as an argument. Then if the string begins with capital letter then return true otherwise return false. But my current function only works for one word string which I want it to work for both one word and a whole sentence. How can I improve my code to achieve this? Secondly, it should not work when numbers are passed inside sentence. How can I do this?
Here is my code
function takeString (str) {
var regex = /^[A-Za-z]+$/;
if (str.match(regex)) {
if (str.charAt(0) === str.toUpperCase().charAt(0)) {
alert('true');
return true;
} else {
alert('false');
return false;
}
} else {
alert('Only letters please.');
}
}
takeString('This is'); // shows Only letters please which is wrong. this should work
takeString('String); // returns true which right
takeString('string'); // returns false which is right
takeString('This is 12312321'); // shows only letters please which is right bcoz it has digits
takeString('12312312'); // show Only letters please which is right.
​

Spaces aren't letters. You have to add them into your character set:
> 'This is a string'.match(/^[A-Za-z]+$/);
null
> 'This is a string'.match(/^[A-Za-z\s]+$/);
["This is a string"]
\s matches all whitespace, so if you don't want to match tabs, replace \s with a space.
Here's a slightly more condensed version of your code:
function takeString(str) {
return str.match(/^[A-Z][A-Za-z ]*$/);
}

along with the regex advice given by Blender, you'll want to also do the following (in order to satisfy the need to check each word ... assuming words are space or tab separated only:
use the split function to break the string into words ( var mywords = str.split(/\s+/) )
iterate over mywords array returned by split, checking each array element against the regex
return an error if the regex doesnt match
return success if you match every word
takeString (str) {
var mywords = str.split(/\s+/);
for (i = 0; i < mywords.length; i++) {
if (str.match(/^[A-Z][A-Za-z]*$/) != true) {
return false;
}
}
return true;
}
(someone needs to check my js ... )

Related

Javascript remove all characters by regex rules

Who can help me with the following
I create a rule with regex and I want remove all characters from the string if they not allowed.
I tried something by myself but I get not the result that I want
document.getElementById('item_price').onkeydown = function() {
var regex = /^(\d+[,]+\d{2})$/;
if (regex.test(this.value) == false ) {
this.value = this.value.replace(regex, "");
}
}
The characters that allowed are numbers and one komma.
Remove all letters, special characters and double kommas.
If the user types k12.40 the code must replace this string to 1240
Who can help me to the right direction?
This completely removes double occurrences of commas using regex, but keeps single ones.
// This should end up as 1,23243,09
let test = 'k1,23.2,,43d,0.9';
let replaced = test.replace(/([^(\d|,)]|,{2})/g, '')
console.log(replaced);
I don't believe there's an easy way to have a single Regex behave like you want. You can use a function to determine what to replace each character with, though:
// This should end up as 1232,4309 - allows one comma and any digits
let test = 'k12,3.2,,43,d0.9';
let foundComma = false;
let replaced = test.replace(/(,,)|[^\d]/g, function (item) {
if (item === ',' && !foundComma) {
foundComma = true;
return ',';
} else {
return '';
}
})
console.log(replaced);
This will loop through each non-digit. If its the first time a comma has appeared in this string, it will leave it. Otherwise, if it must be either another comma or a non-digit, and it will be replaced. It will also replace any double commas with nothing, even if it is the first set of commas - if you want it to be replaced with a single comma, you can remove the (,,) from the regex.

JavaScript: Amend the Sentence

I am having trouble below javaScript problem.
Question:
You have been given a string s, which is supposed to be a sentence. However, someone forgot to put spaces between the different words, and for some reason they capitalized the first letter of every word. Return the sentence after making the following amendments:
Put a single space between the words.
Convert the uppercase letters to lowercase.
Example
"CodefightsIsAwesome", the output should be "codefights is awesome";
"Hello", the output should be "hello".
My current code is:
Right now, my second for-loop just manually slices the parts from the string.
How can I make this dynamic and insert "space" in front of the Capital String?
You can use String.prototype.match() with RegExp /[A-Z][^A-Z]*/g to match A-Z followed by one or more characters which are not A-Z, or character at end of string; chain Array.prototype.map() to call .toLowerCase() on matched words, .join() with parameter " " to include space character between matches at resulting string.
var str = "CodefightsIsAwesome";
var res = str.match(/[A-Z][^A-Z]*/g).map(word => word.toLowerCase()).join(" ");
console.log(res);
Alternatively, as suggested by #FissureKing, you can use String.prototype.repalce() with .trim() and .toLowerCase() chained
var str = "CodefightsIsAwesome";
var res = str.replace(/[A-Z][^A-Z]*/g, word => word + ' ').trim().toLowerCase();
console.log(res);
Rather than coding a loop, I'd do it in one line with a (reasonably) simple string replacement:
function amendTheSentence(s) {
return s.replace(/[A-Z]/g, function(m) { return " " + m.toLowerCase() })
.replace(/^ /, "");
}
console.log(amendTheSentence("CodefightsIsAwesome"));
console.log(amendTheSentence("noCapitalOnFirstWord"));
console.log(amendTheSentence("ThereIsNobodyCrazierThanI"));
That is, match any uppercase letter with the regular expression /[A-Z]/, replace the matched letter with a space plus that letter in lowercase, then remove any space that was added at the start of the string.
Further reading:
String .replace() method
Regular expressions
We can loop through once.
The below assumes the very first character should always be capitalized in our return array. If that is not true, simply remove the first if block from below.
For each character after that, we check to see if it is capitalized. If so, we add it to our return array, prefaced with a space. If not, we add it as-is into our array.
Finally, we join the array back into a string and return it.
const sentence = "CodefightsIsAwesome";
const amend = function(s) {
ret = [];
for (let i = 0; i < s.length; i++) {
const char = s[i];
if (i === 0) {
ret.push(char.toUpperCase());
} else if (char.toUpperCase() === char) {
ret.push(` ${char.toLowerCase()}`);
} else {
ret.push(char);
}
}
return ret.join('');
};
console.log(amend(sentence));

validation function doesn't work

I have created a java script function, it should validate the input character that should contain 10 characters and can contain alphanumeric characters, but this function does not work, please help me
function ValidateNIC(id)
{
var letters = /^[0-9a-zA-Z ]+$/;
while(id.value.length==10)
if(id.value.match(letters))
{
return true;
}
else
{
alert('NIC must have alphanumeric characters only or should contain 10 charaters');
id.focus();
return false;
}
}
With your code as it stands, if the length is not 10, then nothing else happens. A better approach might be:
if ((id.value.length == 10) && id.value.match(letters)) {
return true;
}
alert("NIC must ...");
id.focus();
return false;
You can put all the conditions for validation in Regex like ^[a-zA-Z0-9]{10}$. Note that additional {10} in the regex pattern string for creating a match only when the length is 10 exactly.
Then you can make use of the Regex Object test method, which test the regex pattern against a string and returns true if the match is successful and false otherwise.
Complete modified snippet below with positive and negative test cases.
function ValidateNIC(id){
var aphaPattern10 = /^[a-zA-Z0-9]{10}$/g;
var result = aphaPattern10.test(id.value);
if(!result){
alert('NIC must have alphanumeric characters only or should contain 10 charaters');
//id.focus();
}
return result;
}
var testObjPass = { value : "012345678a"}
console.log(ValidateNIC(testObjPass));
var testObjFail = { value : "012345678a21312"}
console.log(ValidateNIC(testObjFail));
The following code checks the following
NIC must have alphanumeric characters only or should contain 10 charaters.
So if it is only 10 characters then it will not alert else, it will test the regex. Considering id is an object with key value
function ValidateNIC(id)
{
var letters = /^[0-9a-zA-Z ]+$/;
if(id.value.length!==10){
if(id.value.match(letters))
{
return true;
}
else
{
alert('NIC must have alphanumeric characters only or should contain 10 charaters');
id.focus();
return false;
}
}
}

JavaScript: RegEx - Do not return match1 match2 etc

I'm trying to adopt this regex for my needs:
(?:^|\s)(?:https?:\/\/)?(?:\w+(?=\.).)?(?<name>.*).(?<tld>(?<=\.)\w+)
Demo:
https://regex101.com/r/lI2lB4/2
I would like to return a match for all entries like:
www.example.com
example.com
http://example.com
http://www.example.com
but not for
example.
http://www.example
www.example
Now the regex shown above is working fine, but it returns different matches (Match 1, Match 2, ...) - but would like to get only one result: Matching or not matching.
As a result I would like to use
regExDomain.test($regExDomain.test(input.val()))
{
console.log('valid');
}
else
{
console.log('invalid');
}
The problem is: The regEx above seems always to return "valid".
Any ideas how to do that?
The test() function of Regex class should be enough to validate whether the input matches the pattern.
You could do something like this:
var pattern = /^(http[s]?:\/\/)?(www\.)?([^\.]+)\.[^\.]{2,3}$/
var regex = new RegExp(pattern);
for(var i=1; i<=3; i++) {
if ( regex.test( $("#text"+i).text() ) )
$("#isMatch"+i).html("MATCHES");
else
$("#isMatch"+i).html("DOESN'T MATCH");
}
jsfiddle example: http://jsfiddle.net/jyu16m89/1/
The above example will return false for the extended domains (e.g. ".digital" or ".menu" ). If you want to include it in your pattern, replace {2,3} by +
If you want to include subdomains/folders in your pattern (e.g. returning true for entries like http://stackoverflow.com/questions/), remove the dollar sign (this not limiting the string to end there).
You have a grouped regex so it will return match[n] where n is the number of groups that matched. If nothing matches then you'll get null as a result:
function isUrl(myString) {
var match = myString.match('/(?:^|\s)(?:https?:\/\/)?(?:\w+(?=\.).)?(?<name>.*).(?<tld>(?<=\.)\w+)/');
if(match !== null) {
return true;
}
return false;
}

Trouble with Javascript easy coderbyte challenge

I'm attempting to answer this question:
Using the JavaScript language, have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.
Here's my solution:
function SimpleSymbols(str) {
var test;
for (var i =0; i<str.length; i++){
if ((str.charAt(i)!== '+' && str.charAt(i+1) === str.match(/[a-z]/))
||(str.charAt(i+1) === str.match(/[a-z]/) && str.charAt(i+2) !== '+')){
test = false;
break;
}
else if (str.charAt(0) === str.match(/[a-z]/)){
test = false;
break;}
else {
test= true;}
}
return test;
};
I think you can just use two regex and then compare the length of arrays returned by them
function SimpleSymbols(str){
return str.match(/[a-z]/g).length == str.match(/\+[a-z]\+/g).length;
}
The first regex /[a-z]/g will match all the letters and /\+[a-z]\+/g will match all the letters which are followed and preceded by a literal +.
Then, we just use the Array.length property to check if the lengths are same or not and then return the Boolean result. As simple as that.

Categories

Resources