How can I remove all white spaces? - javascript

I am using the following:
var xpto = "AB23. 3434-.34212 23 42."
I'm removing the "." "-" And ""
xpto.replace(/\./g,"").replace(/\-/g,"").replace("/\s/g","")
How can I remove all white spaces?

Your last replace is using a string, not a regular expression. You also don't seem to have kept the result:
xpto = xpto.replace(/\./g,"").replace(/\-/g,"").replace(/\s/g,"");
// ^ No quotes here -------------------------------^--^
// \--- Remember result
You can also shorten that and just call replace once, using a character class ([...]):
xpto = xpto.replace(/[-.\s]/g,"");
(Note that when using the - character literally in a character class, you must make it the first character after the opening [ or the last character before the closing ], or put a backslash in front of it. If it appears between two other characters ([a-z], for instance), it means "any character in the range".)

You can remove white spaces using replace function
xpto.replace(/\s/g,'');

Your error comes from the quotes around your last regex, however I might also point out that you are calling replace way more than needed:
xpto = xpto.replace(/[\s.-]/g,"");
This will strip out spaces, dots and hyphens.

You done it right, but forgot the quotation marks "" at /\s/g. Also, you want to change the string xpto, to the replaced xpto, so you can now do something with it.
Javascript
var xpto = "AB23. 3434-.34212 23 42."
xpto = xpto.replace(/\./g,"").replace(/\-/g,"").replace(/\s/g,"");
Output
AB233434342122342
JSFiddle demo

Related

How to write regexp for finding :smile: in javascript?

I want to write a regular expression, in JavaScript, for finding the string starting and ending with :.
For example "hello :smile: :sleeping:" from this string I need to find the strings which are starting and ending with the : characters. I tried the expression below, but it didn't work:
^:.*\:$
My guess is that you not only want to find the string, but also replace it. For that you should look at using a capture in the regexp combined with a replacement function.
const emojiPattern = /:(\w+):/g
function replaceEmojiTags(text) {
return text.replace(emojiPattern, function (tag, emotion) {
// The emotion will be the captured word between your tags,
// so either "sleep" or "sleeping" in your example
//
// In this function you would take that emotion and return
// whatever you want based on the input parameter and the
// whole tag would be replaced
//
// As an example, let's say you had a bunch of GIF images
// for the different emotions:
return '<img src="/img/emoji/' + emotion + '.gif" />';
});
}
With that code you could then run your function on any input string and replace the tags to get the HTML for the actual images in them. As in your example:
replaceEmojiTags('hello :smile: :sleeping:')
// 'hello <img src="/img/emoji/smile.gif" /> <img src="/img/emoji/sleeping.gif" />'
EDIT: To support hyphens within the emotion, as in "big-smile", the pattern needs to be changed since it is only looking for word characters. For this there is probably also a restriction such that the hyphen must join two words so that it shouldn't accept "-big-smile" or "big-smile-". For that you need to change the pattern to:
const emojiPattern = /:(\w+(-\w+)*):/g
That pattern is looking for any word that is then followed by zero or more instances of a hyphen followed by a word. It would match any of the following: "smile", "big-smile", "big-smile-bigger".
The ^ and $ are anchors (start and end respectively). These cause your regex to explicitly match an entire string which starts with : has anything between it and ends with :.
If you want to match characters within a string you can remove the anchors.
Your * indicates zero or more so you'll be matching :: as well. It'll be better to change this to + which means one or more. In fact if you're just looking for text you may want to use a range [a-z0-9] with a case insensitive modifier.
If we put it all together we'll have regex like this /:([a-z0-9]+):/gmi
match a string beginning with : with any alphanumeric character one or more times ending in : with the modifiers g globally, m multi-line and i case insensitive for things like :FacePalm:.
Using it in JavaScript we can end up with:
var mytext = 'Hello :smile: and jolly :wave:';
var matches = mytext.match(/:([a-z0-9]+):/gmi);
// matches = [':smile:', ':wave:'];
You'll have an array with each match found.

Replace specific letter in string

If I want to replace a digit in the string, I would do the following:
"a3v".replace(/\d+/,"") // "av"
However, in the string "dynamic_fields[n][key]", I want to replace the n inside the brackets with 1. This is what I have done so far:
"dynamic_fields[n][key]".replace(/^.+[(n)]/,1)
Unfortunately, this is the result it gave me:
"1][key]"
Even though I expected:
"dynamic_fields[1][key]"
How come it doesn't recognize the capturing group () and replace the content in it with 1? What am I doing wrong?
This could be easily done like this:
var string = "dynamic_fields[n][key]";
var replaced = string.replace(/\[n\]/,"\[1\]");
alert(replaced);
Basically, this finds the character "n" that is surrounded with brackets, and replaces it with a "1" surrounded with brackets. Remeber to "escape" the brackets to make them literal. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#String_literals
I hope this helps!
You have to change it to be like that
"dynamic_fields[n][key]".replace(/[(n)]/g,1);
here's the sample running one
http://ideone.com/dzFGqQ

How to allow whitespace in Regex

I have a regex which allows only to enter integers and floats in a text box.
Regex Code:-
("^[0-9]*(?:[.][0-9]*|)$");
But it gives an error when the user enters whitespace at the beginning and end of the entered values. I want the user to allow spaces at the beginning and at the end as optional, so I changed the regex as below but it didn't work.
Note: Spaces may be spaces or tabs.
Test Case: User might enter:
"10","10.23"," 10","10 "," 10.23","10.23 "
Any number of spaces are allowed.
("^(?:\s)*[0-9]*(?:[.][0-9]*|)$")
I am newbie with regex, so any help will be highly appreciated.
Thank you.
Try this:
/^\s*[0-9]*(?:[.][0-9]*|)\s*$/;
You don't have to wrap a single entity in a group to repeat it, and I have added a second zero-or-more-spaces at the end which is what you are missing to make it work.
Note: You have not posted the code you use to create the RegExp object, but if it is new RegExp(string), remember to escape your backslashes (by doubling them):
var r = new RegExp("^\\s*[0-9]*(?:[.][0-9]*|)\\s*$");
Also, as #Blender suggests, this can be simplified to:
/^\s*[0-9]*(?:\.[0-9]*)?\s*$/;
Or, using \d instead of [0-9]:
/^\s*\d*(?:\.\d*)?\s*$/;
You don't necessarily need a Regular Expression: !isNaN(Number(textboxvalue.trim())) would be sufficient.
Otherwise, try /^\s{0,}\d+\.{0,1}\d+\s{0,}$/. Test:
var testvalues = ["10","10.23"," 10","10 "," 10.23","10.23 ","10.24.25"];
for (var i=0;i<testvalues.length;i+=1){
console.log(/^\s{0,}\d+\.{0,1}\d+\s{0,}$/.test(testvalues[i]));
}
//=> 6 x true, 1 x false

Javascript and regex: remove space after the last word in a string

I have a string like that:
var str = 'aaaaaa, bbbbbb, ccccc, ddddddd, eeeeee ';
My goal is to delete the last space in the string. I would use,
str.split(0,1);
But if there is no space after the last character in the string, this will delete the last character of the string instead.
I would like to use
str.replace("regex",'');
I am beginner in RegEx, any help is appreciated.
Thank you very much.
Do a google search for "javascript trim" and you will find many different solutions.
Here is a simple one:
trimmedstr = str.replace(/\s+$/, '');
When you need to remove all spaces at the end:
str.replace(/\s*$/,'');
When you need to remove one space at the end:
str.replace(/\s?$/,'');
\s means not only space but space-like characters; for example tab.
If you use jQuery, you can use the trim function also:
str = $.trim(str);
But trim removes spaces not only at the end of the string, at the beginning also.
Seems you need a trimRight function. its not available until Javascript 1.8.1. Before that you can use prototyping techniques.
String.prototype.trimRight=function(){return this.replace(/\s+$/,'');}
// Now call it on any string.
var a = "a string ";
a = a.trimRight();
See more on Trim string in JavaScript? And the compatibility list
You can use this code to remove a single trailing space:
.replace(/ $/, "");
To remove all trailing spaces:
.replace(/ +$/, "");
The $ matches the end of input in normal mode (it matches the end of a line in multiline mode).
Try the regex ( +)$ since $ in regex matches the end of the string. This will strip all whitespace from the end of the string.
Some programs have a strip function to do the same, I do not believe the stadard Javascript library has this functionality.
Regex Reference Sheet
Working example:
var str = "Hello World ";
var ans = str.replace(/(^[\s]+|[\s]+$)/g, '');
alert(str.length+" "+ ans.length);
Fast forward to 2021,
The trimEnd() function is meant exactly for this!
It will remove all whitespaces (including spaces, tabs, new line characters) from the end of the string.
According to the official docs, it is supported in every major browser. Only IE is unsupported. (And lets be honest, you shouldn't care about IE given that microsoft itself has dropped support for IE in Aug 2021!)

Match word in a string that does not end in ellipsis

Let's say I have the following string:
ZD:123123 ZD:213123 ZD:2e213 [ZD:213123] [ZD#221313] ZD:234...
I want to pattern match every occurrence except ZD:234... because I don't want any words that have an elipses.
This pattern was doing nicely for me in JavaScript:
/(\[|\(|)ZD[:#]\w+(\]|\)|)/g
However, it still captures the ZD:234 part of ZD:234... which I absolutely don't want it to do.
How can I prevent regex from doing this?
An easy fix is to use a negative lookahead:
/(\[|\(|)ZD[:#]\w+\b(\]|\)|)(?!\.\.\.)/g
Note that I've also added \b to avoid matching on ZD:23.
A bit simplified:
/[\[(]?ZD[:#]\w+\b[\])]?(?!\.\.\.)/g
In case you want matching brackets (no [ZD:123)):
/(?:ZD[:#]\w+|\[ZD[:#]\w+\]|\(ZD[:#]\w+\))\b(?!\.\.\.)/g
There is more than one way to skin a cat. The following will work in more browsers by using a simpler regular expression:
function trim(s) {
return s.replace(/^ | $/g,'').replace(/\s+/g,' ');
}
var x = 'ZD:123123 ZD:213123 ZD:2e213... [ZD:213123] [ZD#221313] ZD:234...';
alert(
trim(x.replace(/(^| )[^ ]+[\.]{3}( |$)/g,' ')).split(/\s+/)
);
/* shows: ZD:123123,ZD:213123,[ZD:213123],[ZD#221313] */
It removes any space delimited "word" of characters ending in ... and then splits on the space.

Categories