The chracters match if they are back to back. If the defined illegal characters are part of a long string, the correct sanitized text is not returned. The illegal characters that I want to find and replace with empty space is '-_+=[]{}\|'
I have read various regex blogs, Mozilla Developer Network site, as well as some answers here in stackoverflow. I have used \ for +, [, and |. If there is a more simple way, please, share it.
function dirtyString(str) {
cleanString = str.replace(/-_\+=\[]{}\|/g, "");
return cleanString;
}
For most of sample codes I have run, I don't get anything returned. I have run on Codepen and jsfiddle.
Put your characters into a character class (inside brackets)
A character class will math every character in it. For example, the regex /[abc]/g would match all of the a's, b's, and c's (the character class is [abc]. Also, the character class [a-zA-Z0-9] (which you might see a lot) matches all alphanumeric characters
Use a / before the brackets ([]). See more here.
var string = "s[s ass'-sas_+as[aasd]{ss}\asddfa|a]fasdf";
string = string.replace(/[ '-_+=\[\]{}\|]/g, '');
console.log(string);
Try putting your characters into a regex character class:
function dirtyString(str) {
cleanString = str.replace(/[\-_+=\[\]{}\\|]/g, "");
return cleanString;
}
var str = "HELLO-_+=[]{}|WORLD";
console.log(str);
console.log(dirtyString(str));
Note: You should escape square brackets and backslash even if inside a regex character class (not always true in every flavor of regex though).
You need to select them via a character class ([]);
function dirtyString(str) {
cleanString = str.replace(/[\-_+=\[\]{}\\|]/g, "");
return cleanString;
}
var string = "This -str_+in=g[ ]is {d}i|rty.";
console.log(dirtyString(string));
Related
I'm trying to check for every occurrence that a string has an # at the beginning of a string.
So something like this works for only one string occurance
const comment = "#barnowl is cool"
const regex = /#[a-z]/i;
if (comment.charAt(0).includes("#")) {
if (regex.test(comment)) {
// do something
console.log('test passeed')
} else {
// do something else
}
} else {
// do other
}
but....
What if you have a textarea and a user uses the # multiple times to reference another user this test will no longer work because charAt(0) is looking for the first character in a string.
What regex test is doable in a situation where you have to check the occurrence of a # followed by a space. I know i can ditch charAt(0) and use comment.includes("#") but i want to use a regex pattern to check if there is space after wards
So if user does #username followed by a space after words, the regex should pass.
Doing this \s doesn't seem to make the test pass
const regex = /#[a-z]\s/i; // shouldn't this check for white space after a letter ?
demo:
https://jsbin.com/riraluxape/edit?js,console
I think your expression is very close. There are two things that are missing:
The [a-z] match is only looking for one character, so in order to look for multiple characters it needs to be [a-z]+.
The flags section is missing the g modifier, which enables the expression to look through the entire text string instead of just the first match.
I believe the regular expression declaration should be adjusted to the following:
const regex = /#[a-z]+\s/ig;
Is this what you want? Matching all the occurrences of the mention?
const regex = /#\w+/ig
I used the \w flag here which matches any word character.
To check for multiple matches instead of only the first one, append g to the regex:
const regex = /#[a-z]*\s/ig;
Your regex with \s actually works, see: https://regex101.com/r/gyMyvB/1
I have a username field in my form. I want to not allow spaces anywhere in the string. I have used this regex:
var regexp = /^\S/;
This works for me if there are spaces between the characters. That is if username is ABC DEF. It doesn't work if a space is in the beginning, e.g. <space><space>ABC. What should the regex be?
While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:
var regexp = /^\S*$/; // a string consisting only of non-whitespaces
Use + plus sign (Match one or more of the previous items),
var regexp = /^\S+$/
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex #Bergi mentioned just the string version for new RegExp constructor
This will help to find the spaces in the beginning, middle and ending:
var regexp = /\s/g
This one will only match the input field or string if there are no spaces. If there are any spaces, it will not match at all.
/^([A-z0-9!##$%^&*().,<>{}[\]<>?_=+\-|;:\'\"\/])*[^\s]\1*$/
Matches from the beginning of the line to the end. Accepts alphanumeric characters, numbers, and most special characters.
If you want just alphanumeric characters then change what is in the [] like so:
/^([A-z])*[^\s]\1*$/
I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input
Plan A: it's such a simple function... it's ridiculous, really. I'm either totally misunderstanding how RegEx works with string replacement, or I'm making another stupid mistake that I just can't pinpoint.
function returnFloat(str){
console.log(str.replace(/$,)( /g,""));
}
but when I call it:
returnFloat("($ 51,453,042.21)")
>>> ($ 51,453,042.21)
It's my understanding that my regular expression should remove all occurrences of the dollar sign, the comma, and the parentheses. I've read through at least 10 different posts of similar issues (most people had the regex as a string or an invalid regex, but I don't think that applies here) without any changes resolving my issues.
My plan B is ugly:
str = str.replace("$", "");
str = str.replace(",", "");
str = str.replace(",", "");
str = str.replace(" ", "");
str = str.replace("(", "");
str = str.replace(")", "");
console.log(str);
There are certain things in RegEx that are considered special regex characters, which include the characters $, ( and ). You need to escape them (and put them in a character set or bitwise or grouping) if you want to search for them exactly. Otherwise Your Regex makes no sense to an interpreter
function toFloat(str){
return str.replace(/[\$,\(\)]/g,'');
}
console.log(toFloat('($1,234,567.90'));
Please note that this does not conver this string to a float, if you tried to do toFloat('($1,234,567.90)')+10 you would get '1234568.9010'. You would need to call the parseFloat() function.
the $ character means end of line, try:
console.log(str.replace(/[\$,)( ]/g,""));
You can fix your replacement as .replace(/[$,)( ]/g, "").
However, if you want to remove all letters that are not digit or dot,
and easier way exists:
.replace(/[^\d.]/g, "")
Here \d means digit (0 .. 9),
and [^\d.] means "not any of the symbols within the [...]",
in this case not a digit and not a dot.
if i understand correctly you want to have this list : 51,453,042.21
What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).
Syntax: [characters] where characters is a list with characters to be drop( in your case $() ).
The g means Global, and causes the replace call to replace all matches, not just the first one.
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$()]/g, "")); //51,453,042.21
if you want to delete ','
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$(),]/g, "")); //51453042.21
I want to validate a string that does not allows the following characters.
<,>,:,","/,\,|,?,*,#
I want to validate this through JavaScript.
I was trying this with the following code.
var reg = /[^a-zA-Z0-9 \-_]+/;
reg.test(filename[0])
But this was unable to validating the symbol #.
Please help.
The problem you have is that you included the hyphen in the middle of the pattern without escaping it. This tells the engine that you are expecting a range--in this case space through underscore. It's easier (in my opinion) to place the hyphen as either the first or last character in the pattern, at which point you don't have to escape it. (It would be the second character if you are using a negated character class.)
e.g.
var reg = /[^a-zA-Z0-9 \-_]+/;
--OR--
var reg = /[^a-zA-Z0-9 _-]+/;
--OR--
var reg = /[^-a-zA-Z0-9 _]+/;
Do you only want to allow English letters a-z (and A-Z), numbers, the space, '_', and '-'? If so, that is different than disallowing the characters you specified since '☃' doesn't have the characters you provided but may not be a valid string in your use case.
In the case you just want the English alphabet, numbers, space, '_', and '-', you can use the following RegExp and conditional:
var reg = /^[a-zA-Z0-9 \-_]+$/;
if (reg.test(filename[0])) {
// String is ok
}
This says everything in the string between beginning (^) and end ($) must be one or more of the allowed characters.
If you want to disallow the characters you provided in your question, you can use:
var reg = /[\<\>\:\,\/\\\|\?\*\#]/;
if (!reg.test(filename[0])) {
// String is ok
}
This says to search for any of the characters you've listed (they are all escaped with a \ before them) and if you find any, the string is invalid. So only if the test fails is the string a valid string - that's why there's a ! before the test.
string sourceString ="something" ;
var outString = sourceString.replace(/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');