Change a string with javascript - javascript

I'm checking a string with this regular expression:/^[SE]*[\s]*[0-9]{3}[\s\-]*[0-9]{2}$/. This allows a total of 9 different formats, being: XXXXX, XXX-XX, XXX XX, SEXXXXX, SEXXX-XX, SEXXX XX, SE XXXXX, SE XXX-XX and SE XXX XX (X:s being any number from 0-9). How do I change the format to XXXXX after the check passes for one of the 9 valid formats?
I've read a bunch of other threads about the string.replace()-method but I can't seem to make it work. Here's my code so far:
var pcValue = postalCode.value;
var format = /^[SE]*[\s]*[0-9]{3}[\s\-]*[0-9]{2}$/;
if (format.test(pcValue) === true) {
pcValue = pcValue.replace(/\[SE]*[\s]*[\s\-]*$/, /^[0-9]{5}$/);
}
What it gives me is a string with /^[0-9]{5}$/ instead of the XXXXX format I wanted.

You can do this :
var format = /^([SE]*)\s*(\d{3})[\s\-]*(\d\d)$/;
if (format.test(pcValue)) {
pcValue = pcValue.replace(format, "$2$3");
}
Note that if you don't do anything else than replacing if test returns true, then you don't have to test at all, just execute the replacement.

Try this:
var pcValue = postalCode.value;
pcValue = pcValue.replace(/^[SE]*[\s]*([0-9]{3})[\s\-]*([0-9]{2})$/, "$1$2");
Demo
http://jsfiddle.net/uLJEm/

var pcValue = postalCode.value;
var format = /^[SE]*[\s]*[0-9]{3}[\s\-]*[0-9]{2}$/;
if (format.test(pcValue) === true) {
pcValue = pcValue.replace(/\[SE]*[\s]*[\s\-]*$/, /^[0-9]{5}$/);
}
str.replace(original,replicant);

The answer you've marked as accepted also validates these kinds of inputs :
"ES 12345"
"SSSSS 123 - 45"
"SESE 123---45"
The following regular expression might better fit with your needs :
function parse(input) {
var re = /^(?:SE)?\s?(\d{3})(?:\s|-)?(\d\d)$/;
return re.test(input) && input.replace(re, '$1$2');
}
var input1 = parse('SE 123 45'); // 12345
var input2 = parse('ES 123 45'); // false
input1 || alert('Please fix input #1!');
input2 || alert('Please fix input #2!'); // alert!
A little help about /^(?:SE)?\s?(\d{3})(?:\s|-)?(\d\d)$/ :
^...$ string boundaries
(...) capture match
(?:...) don't capture match
(?:SE)? "SE", zero or one time
\s? a whitespace, zero or one time
(\d{3}) 3 digits (captured -> $1)
(?:\s|-)? a whitespace or a dash, zero or one time
(\d\d) 2 digits (captured -> $2)
More on regular expressions : http://www.javascriptkit.com/javatutors/redev.shtml.

Related

regular expression for numeric value; at most 3 decimal places

I'm trying to validate a form using regular expressions, the conditions are:
It has to be a numeric value
It CAN have up to three decimal places(0,1,2 are allowed too)
It has to be divided by a comma(,)
I already got it to work using HTML5-Patterns with this:
pattern='\d+(,\d{1,3})?'
Since patterns are not supported by IE9, I tried doing it with js:
var numPattern = /\d+(,\d{1,3})?/;
if(!numPattern.test(menge.val()))
{
checkvalidate = false;
}
Where did I go wrong?
Examples
valid: 1,234 ; 2,00 ; 5 ; 0,1
invalid: 1,2345 ; 2.00 ; 56a
You'll need to start your regex with ^ and end it with $ to make sure the entire input string/line is matched.
/^\d+(,\d{1,3})?$/
Here's a "demo" in which all your examples are valid/invalid:
https://regex101.com/r/oP5yJ4/1
(Using regex101.com to debug your regular expression patterns is often very useful)
Note that: (without ^ and $)
var pattern_without = /\d+(,\d{1,3})?/;
pattern_without.test("56a") === true; // matches, but only "56"
pattern_without.test("1,2345") === true; // matches, but only "1,234"
but: (with ^ and $)
var pattern_with = /^\d+(,\d{1,3})?$/;
pattern_with.test("56a") === false; // no match
pattern_with.test("1,2345") === false; // no match
You can use this regex:
/^\d+(?:,\d{1,3})*$/
RegEx Demo
Try this expression:
\d+(,\d{3})*([.]\d{1,3})?
Valid examples:
1,200.123
1,200.12
1,200.1
1.123
1,200,222
1,200,002
You can use the RegExp object.
var str = "123545,123";
var patt = new RegExp("/^(?:\d*\,\d{1,3}|\d+)$/");
var res = patt.test(str);
After execution, res will be true, since str matches the pattern you're looking for,

Issue with simple regex javascript

String = "Part # 12345 MSRP $16.55
I simply want to be able to grab the numbers "12345" so I made it between # and M. the regular expression i came up with is....
....text().match(/#(.*)M/)
Since there is no digit before the part you want to extract, you can use following
var num = String.match(/\d+/)[0];
match returns an array or null. You can use
string.match(/#\s*(\d+)\s*M/)[1]
If needed, add a test :
var m = string.match(/#\s*(\d+)\s*M/);
if (m) {
var num = +m[1]; // the first captured group is at index 1
console.log('number : ', num);
} else {
console.log('no number')
}

javascript regexp, select from certain type of url

I'm making a url filter using javascript
i get a parameter from url
parameter 1 = /name/123
//description /text/number
parameter 2 = /name/name/121
//description /text/text/number
var filter = /[/a-z][/][0-9]/;
if(filter.test(page) == true){
//do code;
}
I made it to select a parameter 1, however it selects parameter 2 too.
what should I fix to select the only parameter 1 or parameter 2 separately?
Thank you.
Try this:
var filter = /^\/[^/]+\/\d+$/;
// or
var filter = /^\/[a-z]+\/\d+$/i;
That is to say that you can match on:
^ beginning of string
\/ a / (escaped for the regex literal)
[^/]+ one or more non-slash characters in a row, or
[a-z]+ one or more letters in a row
\/ another slash
\d+ one or more digits
$ end of string
Note also that your if test doesn't need the ==true part, you can just say:
if(filter.test(page)){
The pattern you use is invalid, it matches only one character followed by / followed by one digit.
Try using this pattern:
PATTERN
/^\/[a-z]+?\/\d+$/
INPUT
1. /name/name/121
2. /name/123
OUTPUT
1. false
2. true
I've slightly modified nnnnnn's version by the addition of a quantifier : (this pattern){n times} which gives /^(\/[^/]+){n}\/\d+$/. See nnnnnn's answer for more details.
function createRegex(n) {
return new RegExp(
'^(\\/[^/]+){' + n + '}\\/\\d+$'
);
}
var twoParts = createRegex(2);
twoParts.test('/part1/part2/123'); // true
twoParts.test('/part1/part2/part3/123'); // false
To split the url into multiple parts :
var parts = '/part1/part2/123'.match(/[^/]+/g);
var part1 = parts[0]; // "part1"
var part2 = parts[1]; // "part2"
var part3 = parts[2]; // "123"
Be careful though, match returns null in case of failure.

Parsing number from string

How do I split selected value, seperate the number from text in jQuery?
Example:
myselect contains c4
Just get only the number 4.
$('select#myselect').selectToUISlider({
sliderOptions: {
stop: function(e,ui) {
var currentValue = $('#myselect').val();
alert(currentValue);
var val = currentValue.split('--)
alert(val);
}
}
});
You can use regex to pull only the numbers.
var value = "c4";
alert ( value.match(/\d+/g) );
edit: changed regex to /\d+/g to match numbers greater than one digit (thanks #Joseph!)
1) if it's always : 1 letter that followed by numbers you can do simple substring:
'c4'.substring(1); // 4
'c45'.substring(1); // 45
2) you can also replace all non-numeric characters with regular expression:
'c45'.replace(/[^0-9]/g, ''); // 45
'abc123'.replace(/[^0-9]/g, ''); // 123
If you know that the prefix is always only one character long you could use this:
var val = currentValue.substr(1);

How to check for uppercase alphabets in an input string, using jQuery

I am using following code snippet, but its not working :-(
//First four characters of input Text should be ALPHABATES (Letters)
if (($("#txtId").val()).length >= 4) {
var firstFourChars = $("#txtId").val().substring(0, 4);
var pattern = new RegExp('[^A-Z]');
if (firstFourChars.match(pattern))
isValid = true;
else
isValid = false;
}
change /[^A-Z]/ to /^[A-Z]/
example :
var a = "ABCJabcd";
console.log(a.match(/^[A-Z]{4}/));
you don't need to use substring(). Your regexp can do all the work for you. The RegExp you are using matches against characters that are NOT between A and Z. As Avinash said, ^[A-Z]{4} will match if your first 4 characters are uppercase. "^" at the beginning of your regexp tells that the following should be the beginning of the string. When placed inside square brackets, it reverts the range of characters you want to match.
The regex should be /[^A-Z]{4}/ if you want to match the 4 lowercase characters.
To detect in the middle of the big papers change /^[A-Z]/ to /[A-Z]/
Example text: " asşldla ABCJ abcd AÇALASD"
$('.Order input').change(function (){ucheck($(this).val())});
$('.Order input').keyup(function (){ucheck($(this).val())});
function ucheck(a) {
if(a.match(/[A-ZĞÜŞİÖÇ]{4}/)){
$('.Order #Error').html(' UPPERCASE');
}else{$('.Order #Error').html('Capitalize');}
}
If they need to be capital:
const startsWithCapitals = /^[A-Z]{4}/.test(string);
Or if they just need to be letters, add an i for ignore case:
const startsWithLetters = /^[a-z]{4}/i.test(string);
^ means start of the string and {number} means x copies

Categories

Resources