How can my regex for finding multiple spaces not match newlines? - javascript

I run this regex on #q keyup event to avoid extra spaces in a string.
$('#q').val($('#q').val().replace(/\s+/g,' '));
The problem is that it is also deleting all new lines. How can I delete extra spaces but keep new lines intact?

The issue is that \s represents all whitespace including newlines. If you just want spaces, you can have a literal space:
$('#q').val($('#q').val().replace(/ +/g,' '));
If you want spaces and tabs, you could use a character class instead:
$('#q').val($('#q').val().replace(/[\t ]+/g,' '));

Looking for \x20+ does the trick:
$('#q').val($('#q').val().replace(/\x20+/g,' '));
20 is the Hex code for the space character. You were looking for all whitespace characters, including newlines.

Related

Replace comma as separator

I am trying to build a Regex to replace commas used as a separator in between normal text.
Different ways I can replace that is valid:
Space before comma
Comma is between text and/or numbers, without any space
Several commas after each other
Example:
"This is a text separated with comma, that I try to fix. , It can be split in several ways.,1234321 , I try to make all the examples in one string,,4321,"
Results:
This is a text separated with comma, that I try to fix.
It can be split in several ways.
1234321
I try to make all the examples in one string
4321
This is the code I have so far using Node.js / Javascript:
data.replace(/(\S,\S)|( ,)|(,,)|(,([a-z0-9]))/ig,';')
The answer from #torazaburo work best, except for several commas with space in-between (, , , ,)
console.log(str.split(/ +, *|,(?=\w|,|$)/));
var str = "This is a text separated with comma, that I try to fix. , It can be split in several ways.,1234321 , I try to make all the examples in one string,,4321,";
console.log(str.split(/ +, *|,(?=\w|,|$)/));
This will split on any comma preceded by one or more spaces, no matter what follows (and eat the preceding spaces, and following spaces if any); or, any comma followed by an alphanumeric or comma or end-of-string.
There is no easy way with the regexp to get rid of the final empty string in the result, caused by the comma at the very end of the input. You can get rid of that yourself if you don't want it.
To rejoin with semi-colon, add .join(';').
data.replace(/\s*,+\s*/g, ';');
This will yield:
This is a text separated with comma;that I try to fix.;It can be split in several ways.;1234321;I try to make all the examples in one string;4321;
There are three parts to this:
\s*: Match zero or more whitespace characters.
,+: Match one or more commas.
\s*: Match zero or more whitespace characters.
If, instead, you want to replace any number of consecutive commas with a single semi-colon:
data.replace(/,+/g, ';');
Honestly, I'm not sure I understood your requirements. If I did misunderstand, please provide the output string you're expecting.

Regex avoid numeric and special characters and allow space between words

I need validation for Full name text box which should avoid numeric and special characters, but allow space between words. See my JavaScript code here:
function jsPreventNumeric(obj) {
obj.value = obj.value.replace(/[^a-z]/gmi, '').replace(/\s+/g, '');
}
It's working fine except it's not allowing space between words. I don't have much knowledge to edit that regex. Can anyone help me to adjust this regex to allow space also?
\s is the escape sequence for whitespace. So your second replace removes all whitepspaces explicitly. /[^a-z]/ means all characters that are not characters from a-z. Add \s so it only removes characters that are not a-z or whitespace
function jsPreventNumeric(obj){
obj.value.replace(/[^a-z\s]/gmi,"");
}
I dont see the picture. Try this: ^[\\p{L} .'-]+$
Problem solved with:
obj.value = obj.value.replace(/[^a-z\s]/gmi, "");

Regex to allow special characters

I need a regex that will allow alphabets, hyphen (-), quote ('), dot (.), comma(,) and space. this is what i have now
^[A-Za-z\s\-]$
Thanks
I removed \s from your regex since you said space, and not white space. Feel free to put it back by replacing the space at the end with \s Otherwise pretty simple:
^[A-Za-z\-'., ]+$
It matches start of the string. Any character in the set 1 or more times, and end of the string. You don't have to escape . in a set, in case you were wondering.
You probably tried new RegExp("^[A-Za-z\s\-\.\'\"\,]$"). Yet, you have a string literal there, and the backslashes just escape the following characters - necessary only for the delimiting quote (and for backslashes).
"^[A-Za-z\s\-\.\'\"\,]$" === "^[A-Za-zs-.'\",]$" === '^[A-Za-zs-.\'",]$'
Yet, the range s-. is invalid. So you would need to escape the backslash to pass a string with a backslash in the RegExp constructor:
new RegExp("^[A-Za-z\\s\\-\\.\\'\\\"\\,]$")
Instead, regex literals are easier to read and write as you do not need to string-escape regex escape characters. Also, they are parsed only once during script "compilation" - nothing needs to be executed each time you the line is evaluated. The RegExp constructor only needs to be used if you want to build regexes dynamically. So use
/^[A-Za-z\s\-\.\'\"\,]$/
and it will work. Also, you don't need to escape any of these chars in a character class - so it's just
/^[A-Za-z\s\-.'",]$/
You are pretty close, try the following:
^[A-Za-z\s\-'.,]+$
Note that I assumed that you want to match strings that contain one or more of any of these characters, so I added + after the character class which mean "repeat the previous element one or more times".
Note that this will currently also allow tabs and line breaks in addition to spaces because \s will match any whitespace character. If you only want to allow spaces, change it to ^[A-Za-z \-'.,]+$ (just replaced \s with a space).

How to allow Regex expression with Spaces

var validate = /^[##&%][a-zA-Z0-9]{4}$/;
I need to allow the spaces as well in this Regex.
It's exactly as easy as one might think: add a space to the regex where you want to match a space. Spaces work just like any other character in regex.
If you want to match any whitespace character (including tabs, etc.) you can use \s to match any whitespace character.
You need to do this:
var validate = /^[##&%][a-zA-Z0-9 ]{4}$/;
Note, just add a space within the brackets.
if you want just regular space to be allowed then use a normal space in your brackets like this
/^[##&%][a-zA-Z0-9 ]{4}$/
else if you wish to allow all white spaces such as tab or new line use \s:
/^[##&%][a-zA-Z0-9\s]{4}$/

removing space and retaining the new line?

i want to replace all the spaces from a string , but i need to keep the new line character as it ?
choiceText=choiceText.replace(/\s/g,'');
india
aus //both are in differnt line
is giving as indaus
i want newline should retain and remove the s
\s means any whitespace, including newlines and tabs. is a space. To remove just spaces:
choiceText=choiceText.replace(/ /g,''); // remove spaces
You could remove "any whitespace except newlines"; most regex flavours count \s as [ \t\r\n], so we just take out the \n and the \r and you get:
choiceText=choiceText.replace(/[ \t]/g,''); // remove spaces and tabs
You can't use \s (any whitespace) for this. Use a character set instead: [ \t\f\v]
The \s regex pattern matches all whitespace chars. According to MDN, \s is "equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]".
The easiest way to subtract a line feed, a newline, char from \s is to use a reverse, \S, shorthand character class, put it into a negated character class, [^\S] and add \n into it, that is, [^\S\n].
See a JavaScript demo:
console.log(
"india\naus \f\r\t\v\u00a0\u1680\u2000\u200a\u2028\u2029\u202f\u205f\u3000\ufeff."
.replace(/[^\S\n]+/g, ''))

Categories

Resources