Removing any character besides 0-9 + - / * and ^ [duplicate] - javascript

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I'm trying to further my understanding of regular expressions in JavaScript.
So I have a form that allows a user to provide any string of characters. I'd like to take that string and remove any character that isn't a number, parenthesis, +, -, *, /, or ^. I'm trying to write a negating regex to grab anything that isn't valid and remove it. So far the code concerning this issue looks like this:
var pattern = /[^-\+\(\)\*\/\^0-9]*/g;
function validate (form) {
var string = form.input.value;
string.replace(pattern, '');
alert(string);
};
This regex works as intended on http://www.infobyip.com/regularexpressioncalculator.php regex tester, but always alerts with the exact string I supply without making any changes in the calculator. Any advice or pointers would be greatly appreciated.

The replace method doesn't modify the string. It creates a new string with the result of the replacement and returns it. You need to assign the result of the replacement back to the variable:
string = string.replace(pattern, '');

Related

How to use RegEx in JavaScript replace function [duplicate]

This question already has an answer here:
javascript regexp replace not working, but string replace works
(1 answer)
Closed 1 year ago.
Hello team I am new to JS so I am trying to use RegEx with replacing to take input from the user and replace it if it doesn't match the RegEx I have to be able to put 7 digits or 6 digits followed with one letter currently I am doing this
someID.replace('^(([0-9]{1,7})|([0-9]{1,6}[a-zA-Z]{1}))$')
I am not able to replace the current string with the RegEx expression if I enter
12345678900 it remain the same in that situation I need to be 1234567 after the replace or if I have 12345678asd to be 123456a. How can I achieve that by only replace function and a RegEx expresion
You need to use a different regex and a dirrent replace function.
You will also need to get rid of $ if you want to be able to successfully match the string, without worrying about how it ends.
const sampleIDs = [
"123456789000",
"123456abc",
];
sampleIDs.forEach(id => {
const clean = id.match(/^\d{6}[\d\D]/);
console.log(clean[0]);
});

3 Character Long Alphanumeric Regex Not Working [duplicate]

This question already has answers here:
How to detect exact length in regex
(8 answers)
Closed 4 years ago.
So I am trying to use a regular expression to check against strings but it doesn't seem to be working properly.
Basically I want it to match a alpha-numeric string that is exactly 3 characters long. The expression I am using below does not seem to be working for this:
const msg = message.content;
const regex = /[A-Za-z0-9]{3}/g;
if (msg.match(regex)) {
// Do something
}
Am I doing something wrong? Any help would be appreciated. Thanks in advance.
You need to add ^ and $ for the start-of-string anchor and end-of-string anchor, respectively - otherwise, for example, for #123, the 123 will match, and it will pass the regex. You also might consider using the i flag rather than repeat A-Za-z, and you can use \d instead of 0-9.
It looks like you just want to check whether the string passes the regex's test or not, in which case .test (evaluates to a boolean) might be a bit more appropriate than .match. Also, either way, there's no need for the global flag if you're just checking whether a string passes a regex:
const regex = /^[a-z\d]{3}$/i;
if (regex.test(msg)) {
// do something
}

Pattern check returning false javascript/typescript [duplicate]

This question already has answers here:
JavaScript RegExp objects
(5 answers)
Closed 6 years ago.
I am trying to validate if a string I entered matches the date format 'MM/yyyy'
Below is a sample of the code I am using for the same:
var date='05/2016'
var patt= new RegExp('^((0[1-9])|(1[0-2])|[1-9])\/(\d{4})$');
patt.test(date);
However the above code is returning false.
I tried running it with the regex checker:
https://regex101.com/
The pattern seems to be working fine.
Could someone please let me know what is missing.
https://jsfiddle.net/ymj6o8La/
You have to escape the string that is passed to RegExp (the backslashes).
var patt= new RegExp('^((0[1-9])|(1[0-2])|[1-9])\\/(\\d{4})$');
Even better, in your case, it's not dynamic, so you should use the literal RegExp instead
var patt = /^((0[1-9])|(1[0-2])|[1-9])\/(\d{4})$/
You should escape your backslashes. To represent \d or even \ you should another backslash behind it (e.g: \\) :
var date = '05/2016'
var patt = new RegExp('^((0[1-9])|(1[0-2])|[1-9])\\/(\\d{4})$');
console.log(patt.test(date));
Try using a pattern like this
patt= /^((0[1-9])|(1[0-2]))\/(\d{4})$/;

Replace '-' with '--' in a JavaScript string [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I am trying to replace a single dash '-' character in a string with double dashes.
2015–09–01T16:00:00.000Z
to be
2015-–09-–01T16:00:00.000Z
This is the code I am using but it doesn't seem to be working:
var temp = '2015–09–01T16:00:00.000Z'
temp.replace(/-/g,'--')
In JavaScript Strings are immutable. So, when you modify a string, a new string object will be created with the modification.
In your case, the replace has replaced the characters but returns a new string. You need to store that in a variable to use it.
For example,
var temp = '2015–09–01T16:00:00.000Z';
temp = temp.replace(/–/g,'--');
Note The string which you have shown in the question, when copied, I realised that it is a different character but looks similar to – and it is not the same as hyphen (-). The character codes for those characters are as follows
console.log('–'.charCodeAt(0));
// 8211: en dash
console.log('-'.charCodeAt(0));
// 45: hyphen
The hyphen character – you have in the string is different from the one you have in the RegExp -. Even though they look alike, they are different characters.
The correct RegExp in this case is temp.replace(/–/g,'--')
Probably the easiest thing would be to just use split and join.
var temp = '2015–09–01T16:00:00.000Z'.split("-").join("--");

Replacing a colon using string replace using Javascript and jQuery [duplicate]

This question already has answers here:
Replace method doesn't work
(4 answers)
Closed 4 years ago.
I have a simple string that I'm trying to manipulate:
Your order will be processed soon:
I grab the string using:
var html = jQuery('.checkout td h4').html();
I then try to replace the ':' using:
html.replace(":", ".");
When I print it out to the console, the string is the same as the original string. I've also tried making sure that the html variable is of type "string" by doing the following:
html = html + "";
That doesn't do anything. In searching around, it seems that the replace function does a RegEx search and that the ":" character might have a special meaning. I do not know how to fix this. Can someone help me get rid of this stinkin' colon?
Slightly related...
I couldn't get these answers to work to replace all ":" in a string for the url encoded character %3a and modified this answer by'xdazz' to work: Javascript: Replace colon and comma characters to get...
str = str.replace(/:\s*/g, "%3a");
In your case it would be
str = str.replace(/:\s*/g, ".");
If you wanted to replace all colons with periods on a longer string.
Hope this helps somebody else.
The replace function returns a new string with the replacements made.
Javascript strings are immutable—it cannot modify the original string.
You need to write html = html.replace(":", ".");
I think c++ is the only high level language where strings are mutable. This means that replace cannot modify the string it operates on and so must return a new string instead.
Try the following instead
var element = jQuery('.checkout td h4');
element.html(element.html().replace(":", "."));
Or, perhaps more correctly (since you may have multiple elements).
jQuery('.checkout td h4').html(
function (index, oldHtml) {
return oldHtml.replace(":", ".");
}
);

Categories