Javascript remove all characters by regex rules - javascript

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.

Related

Javascript Regex - replacing characters based on regex rules

I am trying to remove illegal characters from a user input on a browser input field.
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(???, ""))
}
I can test with the right regex and it works just fine. Now I am trying to remove the illegal characters. The rules are, only lower case alpha character in the first position. All remaining positions can only have lower case alpha and numbers 0-9. No spaces or special characters. I am not sure what pattern to use on the replace line.
Thanks for any help you can provide.
Brad
You could try the below code:
const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
console.log('success',myInput)
} else {
console.log("fail",myInput.replace(/[^a-z0-9]/g, ""))
}
Replace is using the following regexp: /[^a-z0-9]/g. This matches all characters that are not lowercase or numeric.
You can validate your regexp and get help from cheatsheet on the following page: https://regexr.com/
You could handle this by first stripping off any leading characters which would cause the input to fail. Then do a second cleanup on the remaining characters:
var inputs = ['abc123', '46432e66Sc'];
inputs.forEach(i => console.log(i + " => " + i.replace(/^[^a-z]+/, "")
.replace(/[^a-z0-9]+/g, "")));
Note that after we have stripped off as many characters as necessary for the input to start with a lowercase, the replacement to remove non lowercase/non digits won't affect that first character, so we can just do a blanket replacement on the entire string.

add a dash to a specific digits entered by the user

I did find this function in jQuery that add a dash after very four numbers, but I would like to add a dash to a number entered by the user with the follow format:
1234-1234556-123-1
but I could manage to get it, could you please help me, this is the jQuery function that formats the follow: 1234-1234-1234-1
$('.creditCardText').keyup(function() {
var foo = $(this).val().split("-").join(""); // remove hyphens
if ((foo.length > 0) && (foo.length < 14)) {
foo = foo.match(new RegExp('.{1,4}', 'g')).join("-");
}
$(this).val(foo);
});
You need to use parenthetical matching groups. Put the pattern in parenthesis. This will return an array with the whole match, followed by the parenthetical matches, followed by some match info. So, you have to slice out array elements 1-4, and then join them with dashes. Because some of the matches may be empty, you can clean up with another replace that removes trailing dashes:
Edit: You could also remove all non-numeric characters, instead of just hyphens. (See second line)
$('.creditCardText').keyup(function() {
var foo = $(this).val().replace(/\D/g, ""); // remove non-numerics
if ((foo.length > 0) && (foo.length < 16)) {
foo = foo.match(new RegExp('(\\d{1,4})(\\d{0,7})(\\d{0,3})(\\d?)')).slice(1,5).join("-").replace(/\-+$/, '');
}
$(this).val(foo);
});
Demo: https://jsfiddle.net/oohfksjd/
It is more RegExp issue, not JavaScript.
RegExp('(.{1,4})(.{1,7})(.{1,3})(.{1,1})', 'g')

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));

How to match one, but not two characters using regular expressions

Using javascript regular expressions, how do you match one character while ignoring any other characters that also match?
Example 1: I want to match $, but not $$ or $$$.
Example 2: I want to match $$, but not $$$.
A typical string that is being tested is, "$ $$ $$$ asian italian"
From a user experience perspective, the user selects, or deselects, a checkbox whose value matches tags found in in a list of items. All the tags must be matched (checked) for the item to show.
function filterResults(){
// Make an array of the checked inputs
var aInputs = $('.listings-inputs input:checked').toArray();
// alert(aInputs);
// Turn that array into a new array made from each items value.
var aValues = $.map(aInputs, function(i){
// alert($(i).val());
return $(i).val();
});
// alert(aValues);
// Create new variable, set the value to the joined array set to lower case.
// Use this variable as the string to test
var sValues = aValues.join(' ').toLowerCase();
// alert(sValues);
// sValues = sValues.replace(/\$/ig,'\\$');
// alert(sValues);
// this examines each the '.tags' of each item
$('.listings .tags').each(function(){
var sTags = $(this).text();
// alert(sTags);
sSplitTags = sTags.split(' \267 '); // JavaScript uses octal encoding for special characters
// alert(sSplitTags);
// sSplitTags = sTags.split(' \u00B7 '); // This also works
var show = true;
$.each(sSplitTags, function(i,tag){
if(tag.charAt(0) == '$'){
// alert(tag);
// alert('It begins with a $');
// You have to escape special characters for the RegEx
tag = tag.replace(/\$/ig,'\\$');
// alert(tag);
}
tag = '\\b' + tag + '\\b';
var re = new RegExp(tag,'i');
if(!(re.test(sValues))){
alert(tag);
show = false;
alert('no match');
return false;
}
else{
alert(tag);
show = true;
alert('match');
}
});
if(show == false){
$(this).parent().hide();
}
else{
$(this).parent().show();
}
});
// call the swizzleRows function in the listings.js
swizzleList();
}
Thanks in advance!
Normally, with regex, you can use (?<!x)x(?!x) to match an x that is not preceded nor followed with x.
With the modern ECMAScript 2018+ compliant JS engines, you may use lookbehind based regex:
(?<!\$)\$(?!\$)
See the JS demo (run it in supported browsers only, their number is growing, check the list here):
const str ="$ $$ $$$ asian italian";
const regex = /(?<!\$)\$(?!\$)/g;
console.log( str.match(regex).length ); // Count the single $ occurrences
console.log( str.replace(regex, '<span>$&</span>') ); // Enclose single $ occurrences with tags
console.log( str.split(regex) ); // Split with single $ occurrences
\bx\b
Explanation: Matches x between two word boundaries (for more on word boundaries, look at this tutorial). \b includes the start or end of the string.
I'm taking advantage of the space delimiting in your question. If that is not there, then you will need a more complex expression like (^x$|^x[^x]|[^x]x[^x]|[^x]x$) to match different positions possibly at the start and/or end of the string. This would limit it to single character matching, whereas the first pattern matches entire tokens.
The alternative is just to tokenize the string (split it at spaces) and construct an object from the tokens which you can just look up to see if a given string matched one of the tokens. This should be much faster per-lookup than regex.
Something like that:
q=re.match(r"""(x{2})($|[^x])""", 'xx')
q.groups() ('xx', '')
q=re.match(r"""(x{2})($|[^x])""", 'xxx')
q is None True

Javascript Match on parentheses inside the string

How do I do a .match on a string that has parentheses in the string?
String1.match("How do I match this (MATCH ME)");
None of the answers are getting me what I want. I'm probably just doing it wrong. I tried to make my question basic and I think doing that asked my question wrong. This is the statement I am tring to fix:
$('[id$=txtEntry3]').focus(function () {
if (!DropdownList.toString().match($('[id$=txtEntry2]').val()) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
ErrorMessageIn("The Ingredient number you entered is not valid.");
return;
}
ErrorMessageOut();
});
This works correctly the problem I am running into is when it tries to match a entry from "txtEntry2" that has "()" in it.
Well it's kinda broken but it works for what I need it to do. This is what I did to fix my problem:
$('[id$=txtEntry3]').focus(function () {
if (!StripParentheses(DropdownList).match(StripParentheses($('[id$=txtEntry2]').val())) || $('[id$=txtEntry2]').val().length < 5) {
$('[id$=txtEntry2]').select();
if (!$('[id$=txtEntry2]').val() == "") {
ErrorMessageIn("The Ingredient number you entered is not valid.");
}
return;
}
ErrorMessageOut();
});
function StripParentheses(String){
x = String.toString().replace(/\(/g, '');
x = x.toString().replace(/\)/g, '');
return x;
}
to get all occurences in e.g. ".. (match me) .. (match me too) .." add the g regexp flag
string.match(/\((.*?)\)/g)
this as also an advantage, that you get only list of all occurences. without this flag, the result will include a whole regexp pattern match (as the first item of resulting array)
If you are interested in the part of the string between parenthesis, then you can use /\(([^\)]*)\)/; if you just need to get the full string, then you can you can use /\([^\)]*\)/.
var str = "How do I match this (MATCH ME)";
str.match(/\((.*?)\)/);

Categories

Resources