Basic Regex to remove any space - javascript

I'm looking for a basic regex that removes any space. I want to use it for ZIP code.
Some people insert space after, before or in between the ZIP code.
I'm using /^\d{5}$/ now. I want to expand it to include space removal.
How can this be improved?

(I'm considering you want to remove spaces in your string, not verifying if it is valid even with spaces)
You can substitute one or more spaces (globally)
/\s+/g
by nothing.
zip.replace(/\s+/g, "");
Example in my browser's JS console:
> " 02 1 3 4".replace(/\s+/g, "");
"02134"

Here's a regex you can use instead of your current one to ignore any and all spaces.
/^(\s*\d){5}\s*$/

If you're sanitizing a form input or something, it's probably easiest to use:
zip = zip.replace(/\D/g,'');
you can then validate without a regex, just use the .length property on String.
if(zip.length != 5) alert('failed!');

Related

Is there a way to add .trim() on the back of a jquery selection?

For a project in my JavaScript class we're required to fetch a json object from flickr using their API defined by a set of tags the user enters; I've successfully done that, however I'd like to cover up a few cracks I've made while writing the algorithm.
For my search bar I'm checking:
($('#search').val().length == 0)
In order to make sure they have at least entered something. The problem I'm facing however is that if one is to type in spaces the spaces are still counted as characters.
My question is, is if I can do something like the following:
($('#search').trim().val().length == 0)
It seems, that this by itself doesn't work. Is there something I'm missing?
Any help would be much appreciated! Thanks!
trim() works on strings and removes leading and trailing spaces.
$('#search').trim().val().length
will try to execute trim() on object and thus will throw an error.
You first have to get the value(string) of the element and then trim it.
$('#search') // Select the element
.val() // Get it's value
.trim() // trim leading & trailing spaces
.length // Then get the length
or using jQuery $.trim()
$.trim($('#search').val()).length
Yes, you would want to run trim on the string not the DOM input so simply reverse it to:
($('#search').val().trim().length == 0)

Javascript string validation. How to write a character only once in string and only in the start?

I am writing validation for phone numbers. I need to allow users to write + character only in the begining of input field and prevent users from writing it later in the field.
In other words:
+11111111 - right,
111111111 - right,
+111+111+ - false,
1111+111+ - false
The problem is that I need to perform validation while typing. As result I cannot analyse whole string after submision, thus it is not possible to fetch the position of + character because 'keyup' always returns 0.
I have tryed many approaches, this is one of them:
$('#signup-form').find('input[name="phone"]').on('keyup', function(e) {
// prevent from typing letters
$(this).val($(this).val().replace(/[^\d.+]/g, ''));
var textVal = $(this).val();
// check if + character occurs
if(textVal === '+'){
// remove + from occurring twice
// check if + character is not the first
if(textVal.indexOf('+') > 0){
var newValRem = textVal.replace(/\+/, '');
$(this).val(newValRem);
}
}
});
When I am trying to replace + character with empty string then it is replaced only once which is not enough, because user might type it a cople of times by mistake.
Here is the link to the fiddle: https://jsfiddle.net/johannesMt/rghLowxq/6/
Please give me any hint in this situation. Thanks!
To help you with the current code fix (#Thomas Mauduit-Blin is right that there are a lot more to do here than just allow plus symbol at the beginning only), you may remove any plus symbols that are preceded with any character. Just capture that character and restore with a backreference in the replacement pattern:
$(this).val($(this).val().replace(/[^\d.+]|(.)\++/g, '$1'));
See the updated fiddle and the regex demo.
The pattern is updated with a (.)\++ alternative. (.) captures any character but a newline into Group 1 that is followed with one or more plus symbols, and the contents of Group 1 is placed back during the replacement with the help of $1 backreference.
For better validation Why don't you use Jquery maskedinput library which will do lots of additional task for you without over head for other purpose also
$("#phone").mask("+999-999-9999");
$("#phone").mask("+9999-999-9999");
$("#phone").mask("+99999999999");
If you want to do the validation on your own, you must use a regex.
But, as described in another related thread here:
don't use a regular expression to validate complex real-world data like phone numbers or URLs. Use a specialized library.
You must let the user enter an invalid phone number, and perform the check later, or on form submit and/or on server side for example. Here, you want to take care of the "+" character, but there are lot's of other stuff to do to have a trustable validation.
If your textVal has a +, indexOf will only check for the first occurence. You need to ensure that first character is not checked by indexOf. So use substring to take out first character from the equation.
Simply replace
if(textVal.indexOf('+') > 0){
with
if(textVal.substring(1).indexOf('+') > -1){
Demo

how to compare string with html element

How to compare a string, may be already in variable, with element taken from DOM?
with element like this
"Something here"
when i call this element with .text() method, i dont just get "Something here", but more like
"
Something
here
"
This is not a literal example, i mean my value is returned with additional whitespaces, and therefore i'm not able to compare it with anything, even if i copy whitespaced string from console.
EDIT
Pretty much all answers tell me to use $.trim, i tried it before and it doesnt work, doesnt remove all the whitespaces, still cant compare even with copy/paste from console.log
Trim and Compare:
if("string_to_compare" == $.trim(element.text())) {
//some code
}
You can use trim() to remove the trailing and leading spaces then compare them..
$.trim(x.text()) == 'abc'
$.trim() is used instead of String.trim() because of IE support
You can use $.trim to remove the spaces around the text you have.
$.trim($("selector").text())
The $.trim() function removes all newlines, spaces (including
non-breaking spaces), and tabs from the beginning and end of the
supplied string. If these whitespace characters occur in the middle of
the string, they are preserved, jQuery Doc.
If you do not want a dependency on JQuery, you should instead use a regular expression:
"Some String" == element.innerHTML.replace(/^\s+|\s+$/g, '');
can you specify the version of jquery you're using (+ post your code maybe) ? I've checked a couple of answers and made my own check and they all seem to work just fine.

regex - How do I exclude "%" and "_"?

Im allowing numbers, letters, and special characters except for % and _ in my html textbox. I have the pattern /[a-zA-Z0-9!##$^&*()-+=]/. I think its not the best way to do it because I have to list all special characters except the two mentioned. Is there a way in which I don't have to list all special characters and don't include the two mentioned? BTW, Im using javascript regex.
For the demo please see http://jsfiddle.net/ce8Th/
Please help.
There's no need for that complex loop. Just call replace directly on the whole string:
$(this).val(function (i, v) {
return v.replace(/%|_/g, '');
});
Here's your fiddle: http://jsfiddle.net/ce8Th/1/
You could just do the reverse:
/[%_]/
if (pattern.test( ....
It's also nice to not use regex if you don't have to, not that it makes a big difference in this case:
if ("%_".split().indexOf(text.charAt(i)) > -1) {
A white list is always best. I would recommend keeping what you have except adding a length modifier and start and end characters:
/^[a-zA-Z0-9!##$^&*()-+=]+$/
Would I happen to be corrent in guessing that you are using this user input for a MySQL query involving LIKE to search for partial matches?
If so, don't exclude characters. Instead, escape them on the server-side. For instance:
$output = str_replace(Array("%","_"),Array("\\%","\\_"),$input);

removing phpbb tag using regex javascript

I'm trying to remove a rectangular brackets(bbcode style) using javascript, this is for removing unwanted bbcode.
I try with this.
theString .replace(/\[quote[^\/]+\]*\[\/quote\]/, "")
it works with this string sample:
theString = "[quote=MyName;225]Test 123[/quote]";
it will fail within this sample:
theString = "[quote=MyName;225]Test [quote]inside quotes[/quote]123[/quote]";
if there any solution beside regex no problem
The other 2 solutions simply do not work (see my comments). To solve this problem you first need to craft a regex which matches the innermost matching quote elements (which contain neither [QUOTE..] nor [/QUOTE]). Next, you need to iterate, applying this regex over and over until there are no more QUOTE elements left. This tested function does what you want:
function filterQuotes(text)
{ // Regex matches inner [QUOTE]non-quote-stuff[/quote] tag.
var re = /\[quote[^\[]+(?:(?!\[\/?quote\b)\[[^\[]*)*\[\/quote\]/ig;
while (text.search(re) !== -1)
{ // Need to iterate removing QUOTEs from inside out.
text = text.replace(re, "");
}
return text;
}
Note that this regex employs Jeffrey Friedl's "Unrolling the loop" efficiency technique and is not only accurate, but is quite fast to boot.
See: Mastering Regular Expressions (3rd Edition) (highly recommended).
Try this one:
/\[quote[^\/]+\].*\[\/quote\]$/
The $ sign indicates that only the closing quote element at the end of the string should be used to determine the ending of the quote you're trying to remove.
And i added a "." before the asterisk so that this will match any sign in between. I tested this with your two strings and it worked.
edit: I don't exactly know how you are using that. But just as an addition. If you want the pattern also to match to a string where no attributes are added for example:
[quote]Hello[/quote]
You should change the "+" sign into an asterisk as well like this:
/\[quote[^\/]*\].*\[\/quote\]$/
This answer has flaws, see Ridgerunner's answer for a more correct one.
Here's my crack at it.
function filterQuotes(text)
{
return text.replace(/\[(\/)?quote([^\/]*)?\]/g,"");
}

Categories

Resources