I have string "club160", but I want to get string "club-160", how I can do this? I need to use split() func? For split I need delimiter but there is no comma, or space.
Can somebody help me?
You can do this using a regular expression and a replace operation:
var s = "club160"
var result = s.replace(/([a-z])([0-9])/i, '$1-$2')
But this only replaces something like aaa111 to aaa-111, 111aaa will stay 111aaa
If the string always contains at least one digit or letter, consider:
var s = 'club160';
s.match(/(\d+)|([a-z]+)/ig).join('-'); // club-160
var t = '160club';
t.match(/(\d+)|([a-z]+)/ig).join('-'); // 160-club
It doesn't care about order or how many groups of letters and numbers are present. However, it requires at least one letter or number in the string, otherwise it will throw an error.
As a function, dealing with errors:
function specialSplit(s) {
// Make sure string has at least one letter or digit
if (/\d|[a-z]/i.test(s)) {
return s.match(/(\d+)|([a-z]+)/ig).join('-');
}
// Otherwise return undefined
}
Related
I need to check whether a string contains other than the specified words/sentence (javascript), it will return true if:
it contains an alphabets, except this phrase: ANOTHER CMD
it contains other than specified multiple sequence of numbers for example: ["8809 8805", "8806 8807"] (the numbers are examples I should be able to test the string for any array of numbers)
Thank you!
Yes you can replace all not in the array
const arr = ["ANOTHER CMD","8809 8805", "8809 8805"]
const okContent = str => {
arr.forEach(entry => str = str.replaceAll(entry,""))
return str.trim()==="";
};
console.log(okContent('Has other stuff than ANOTHER CMD and 8809 8805'))
console.log(okContent('8809 8805 ANOTHER CMD 8809 8805'))
I don't know if it's the correct way of doing it but this worked for me:
replace all the valid words with balnk (using replace)
check if the string is left empty
if it's empty, it means that the string does not contain any unwanted string (to check for space you could use trim method)
you can try regex!
use your array of strings as the '|' separated regex value
and check the specified string in the given line. if it presents negate the output.
const regex = /(ANOTHER CMD|8809 8805|8806 8807)/i
console.log(!regex.test('Should not contain word ANOTHER CMD'))
console.log(regex.test('Should contain word ANOTHER CMD'))
var scale = $('#'+fields[i].id+'-scale').val();
var decimalOnly = '/^\s*-?[1-9]\d*(\,\d{1,'+scale+'})?\s*$/';
if(fields[i].value != "" && !(fields[i].value).match(decimalOnly)) {
$(fields[i]).addClass('form-attr-error');
result = false;
}
else {
$(fields[i]).removeClass('form-attr-error');
}
In the above RegEx passing the 'scale' placeholder value & comparing value.match(RegEx) it's not working.
But it as working like this
value.match(/^\s*-?[1-9]\d*(\,\d{1,2})?\s*$/);
please help me on this how can i pass place holder value in place of '2'.
.match will automatically convert a string argument into a regexp; if you want to be explicit about it, you can use the RegExp constructor. But note that slashes are not part of the regexp, they are part of the regexp literal. I.e. these will do the same thing:
foo.match(/a/)
foo.match("a")
foo.match(new RegExp("a"))
These will all do the same thing that is different from the first set:
foo.match(/\/a\/)
foo.match("/a/")
foo.match(new RegExp("/a/"))
The former ones will match one-letter sequence a; the latter ones will match the three-letter sequence /a/.
tl;dr: get rid of slashes in decimalOnly.
In my web page, I have:
var res = number.match(/[0-9\+\-\(\)\s]+/g);
alert(res);
As you can see, I want to get only numbers, the characters +, -, (, ) and the space(\s)
When I tried number = '98+66-97fffg9', the expected result is: 98+66-979
but I get 98+66-97,9
the comma is an odd character here! How can eliminate it?
Its probably because you get two groups that satisfied your expression.
In other words: match mechanism stops aggregating group when it finds first unwanted character -f. Then it skips matching until next proper group that, in this case, contains only one number - 9. This two groups are separated by comma.
Try this:
var number = '98+66-97fffg9';
var res = number.match(/[0-9\+\-\(\)\s]+/g);
// res is an array! You have to join elements!
var joined = res.join('');
alert(joined);
You're getting this because your regex matched two results in the number string, not one. Try printing res, you'll see that you've matched both 98+66-979 as well as 9
String.match returns an array of matched items. In your case you have received two items ['98+66-97','9'], but alert function outputs them as one string '98+66-97,9'. Instead of match function use String.replace function to remove(filter) all unallowable characters from input number:
var number = '98+66-97fffg9',
res = number.replace(/[^0-9\+\-\(\)\s]+/g, "");
console.log(res); // 98+66-979
stringvariable.match(/[0-9\+\-\(\)\s]+/g); will give you output of matching strings from stringvariable excluding unmatching characters.
In your case your string is 98+66-97fffg9 so as per the regular expression it will eliminate "fffg" and will give you array of ["98+66-97","9"].
Its default behavior of match function.
You can simply do res.join('') to get the required output.
Hope it helps you
As per documents from docs, the return value is
An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.
S,your return value contains
["98+66-97", "9"]
So if you want to skip parentheses-captured matched results
just remove g flag from regular expression.
So,your expression should like this one
number.match(/[0-9\+\-\(\)\s]+/); which gives result ["98+66-97"]
var name = "AlbERt EINstEiN";
function nameChanger(oldName) {
var finalName = oldName;
// Your code goes here!
finalName = oldName.toLowerCase();
finalName = finalName.replace(finalName.charAt(0), finalName.charAt(0).toUpperCase());
for(i = 0; i < finalName.length; i++) {
if (finalName.charAt(i) === " ")
finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
}
// Don't delete this line!
return finalName;
};
// Did your code work? The line below will tell you!
console.log(nameChanger(name));
My code as is, returns 'Albert einstein'. I'm wondering where I've gone wrong?
If I add in
console.log(finalName.charAt(i+1));
AFTER the if statement, and comment out the rest, it prints 'e', so it recognizes charAt(i+1) like it should... I just cannot get it to capitalize that first letter of the 2nd word.
There are two problems with your code sample. I'll go through them one-by-one.
Strings are immutable
This doesn't work the way you think it does:
finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
You need to change it to:
finalName = finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
In JavaScript, strings are immutable. This means that once a string is created, it can't be changed. That might sound strange since in your code, it seems like you are changing the string finalName throughout the loop with methods like replace().
But in reality, you aren't actually changing it! The replace() function takes an input string, does the replacement, and produces a new output string, since it isn't actually allowed to change the input string (immutability). So, tl;dr, if you don't capture the output of replace() by assigning it to a variable, the replaced string is lost.
Incidentally, it's okay to assign it back to the original variable name, which is why you can do finalName = finalName.replace(...).
Replace is greedy
The other problem you'll run into is when you use replace(), you'll be replacing all of the matching characters in the string, not just the ones at the position you are examining. This is because replace() is greedy - if you tell it to replace 'e' with 'E', it'll replace all of them!
What you need to do, essentially, is:
Find a space character (you've already done this)
Grab all of the string up to and including the space; this "side" of the string is good.
Convert the very next letter to uppercase, but only that letter.
Grab the rest of the string, past the letter you converted.
Put all three pieces together (beginning of string, capitalized letter, end of string).
The slice() method will do what you want:
if (finalName.charAt(i) === " ") {
// Get ONLY the letter after the space
var startLetter = finalName.slice(i+1, i+2);
// Concatenate the string up to the letter + the letter uppercased + the rest of the string
finalName = finalName.slice(0, i+1) + startLetter.toUpperCase() + finalName.slice(i+2);
}
Another option is regular expression (regex), which the other answers mentioned. This is probably a better option, since it's a lot cleaner. But, if you're learning programming for the first time, it's easier to understand this manual string work by writing the raw loops. Later you can mess with the efficient way to do it.
Working jsfiddle: http://jsfiddle.net/9dLw1Lfx/
Further reading:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
slice() method
You can simplify this down a lot if you pass a RegExp /pattern/flags and a function into str.replace instead of using substrings
function nameChanger(oldName) {
var lowerCase = oldName.toLowerCase(),
titleCase = lowerCase.replace(/\b./g, function ($0) {return $0.toUpperCase()});
return titleCase;
};
In this example I've applied the change to any character . after a word boundary \b, but you may want the more specific /(^| )./g
Another good answer to this question is to use RegEx to do this for you.
var re = /(\b[a-z](?!\s))/g;
var s = "fort collins, croton-on-hudson, harper's ferry, coeur d'alene, o'fallon";
s = s.replace(re, function(x){return x.toUpperCase();});
console.log(s); // "Fort Collins, Croton-On-Hudson, Harper's Ferry, Coeur D'Alene, O'Fallon"
The regular expression being used may need to be changed up slightly, but this should give you an idea of what you can do with regular expressions
Capitalize Letters with JavaScript
The problem is twofold:
1) You need to return a value for finalName.replace, as the method returns an element but doesn't alter the one on which it's predicated.
2) You're not iterating through the string values, so you're only changing the first word. Don't you want to change every word so it's in lower case capitalized?
This code would serve you better:
var name = "AlbERt EINstEiN";
function nameChanger(oldName) {
// Your code goes here!
var finalName = [];
oldName.toLowerCase().split(" ").forEach(function(word) {
newWord = word.replace(word.charAt(0), word.charAt(0).toUpperCase());
finalName.push(newWord);
});
// Don't delete this line!
return finalName.join(" ");
};
// Did your code work? The line below will tell you!
console.log(nameChanger(name));
if (finalName.charAt(i) === " ")
Shouldn't it be
if (finalName.charAt(i) == " ")
Doesn't === check if the object types are equal which should not be since one it a char and the other a string.
I am trying to validate a string, that should contain letters numbers and special characters &-._ only. For that I tried with a regular expression.
var pattern = /[a-zA-Z0-9&_\.-]/
var qry = 'abc&*';
if(qry.match(pattern)) {
alert('valid');
}
else{
alert('invalid');
}
While using the above code, the string abc&* is valid. But my requirement is to show this invalid. ie Whenever a character other than a letter, a number or special characters &-._ comes, the string should evaluate as invalid. How can I do that with a regex?
Add them to the allowed characters, but you'll need to escape some of them, such as -]/\
var pattern = /^[a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/
That way you can remove any individual character you want to disallow.
Also, you want to include the start and end of string placemarkers ^ and $
Update:
As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._
/^[\w&.\-]+$/
[\w] is the same as [a-zA-Z0-9_]
Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:
/^[\w&.\-]*$/
Well, why not just add them to your existing character class?
var pattern = /[a-zA-Z0-9&._-]/
If you need to check whether a string consists of nothing but those characters you have to anchor the expression as well:
var pattern = /^[a-zA-Z0-9&._-]+$/
The added ^ and $ match the beginning and end of the string respectively.
Testing for letters, numbers or underscore can be done with \w which shortens your expression:
var pattern = /^[\w&.-]+$/
As mentioned in the comment from Nathan, if you're not using the results from .match() (it returns an array with what has been matched), it's better to use RegExp.test() which returns a simple boolean:
if (pattern.test(qry)) {
// qry is non-empty and only contains letters, numbers or special characters.
}
Update 2
In case I have misread the question, the below will check if all three separate conditions are met.
if (/[a-zA-Z]/.test(qry) && /[0-9]/.test(qry) && /[&._-]/.test(qry)) {
// qry contains at least one letter, one number and one special character
}
Try this regex:
/^[\w&.-]+$/
Also you can use test.
if ( pattern.test( qry ) ) {
// valid
}
let pattern = /^(?=.*[0-9])(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!##$%^&*]{6,16}$/;
//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format
let reee =pattern .test("helLo123#"); //true as it contains all the above
I tried a bunch of these but none of them worked for all of my tests. So I found this:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$
from this source: https://www.w3resource.com/javascript/form/password-validation.php
Try this RegEx: Matching special charecters which we use in paragraphs and alphabets
Javascript : /^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$/.test(str)
.test(str) returns boolean value if matched true and not matched false
c# : ^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$
Here you can match with special char:
function containsSpecialChars(str) {
const specialChars = /[`!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
return specialChars.test(str);
}
console.log(containsSpecialChars('hello!')); // 👉️ true
console.log(containsSpecialChars('abc')); // 👉️ false
console.log(containsSpecialChars('one two')); // 👉️ false