Javascript Regular Expression Remove Spaces
I would recommend you use the literal notation, and the \s
character class:
//..
return str.replace(/\s/g, '');
//..
There's a difference between using the character class \s
and just ' '
, this will match a lot more white-space characters, for example '\t\r\n'
etc.., looking for ' '
will replace only the ASCII 32 blank space.
The RegExp
constructor is useful when you want to build a dynamic pattern, in this case you don't need it.
Moreover, as you said, "[\s]+"
didn't work with the RegExp
constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s"
(unknown escape)).
Regular expression for removing whitespaces
This can be done in a single String#replace
call:
var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// gives: "tushar is a good boy"
How do I remove all whitespaces except those between words with Regular Expression in Javascript
Method 1
See regex in use here
\B\s+|\s+\B
\B
Matches a location where\b
doesn't match\s+
Matches one or more whitespace characters
const r = /\B\s+|\s+\B/gconst s = ` hello world! , this is Cecy `
console.log(s.replace(r, ''))
Replace all whitespace characters
You want \s
Matches a single white space
character, including space, tab, form
feed, line feed.
Equivalent to
[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
in Firefox and [ \f\n\r\t\v]
in IE.
str = str.replace(/\s/g, "X");
Javascript Regex: How to remove all whitespaces around certain character?
This will do the trick:
var text = 'text ( 4 |-4 | 1 "test" ) [ 0 50 90 ]';text = text.replace(/\s*([|()[\]])\s*/g, '$1');
alert(text)
JavaScript Regex - Remove Whitespace from Start and End
\s
means whitespace characters in regex, like <space>, <tab>, etc.^
means the beginning of the string$
means the end of the string|
means OR (match the left side or the right side)+
means 1 or more (based off of the rule on the left)/a regex/g
theg
means "global", aka "match multiple times" since you could need to match at the beginning AND end
So the regex means:
/^\s+|\s+$/g
/ / Wrap the regex (how you do it in JS)
^\s+ Try to match at the beginning one or more whitespace chars
| Or...
\s+$ Try to match whitespace chars at the end
g Match as many times as you can
String.prototype.replace replaces the match(es) found in the regex with the string provided as the 2nd argument, in this case an empty string.
So the process internally is:
- Look for all sections that match the regex (which will be the whitespace at the beginning and the whitespace at the end
- Replace each match with
""
, removing those matches entirely
let hello = " Hello, World! ";
let wsRegex = /^\s+|\s+$/g;
let result = hello.replace(wsRegex, "");
console.log('"' + result + '"');
Remove white-space after / in a string with RegEx
You may match a forward slash (\/
, escaped since /
is used as a regex delimiter char) and then any 1 or more whitespaces (\s+
) to replace with a backslash:
s = s.replace(/\/\s+/g, '')
Or, capture the forward slash with a capturing group (a pair of unescaped parentheses, (...)
), and replace with a replacement backreference $1
:
s = s.replace(/(\/)\s+/g, '$1')
See the JS demo:
console.log("/abc/ spaces/ more spaces".replace(/\/\s+/g, '/'))console.log("/abc/ spaces/ more spaces".replace(/(\/)\s+/g, '$1'))
Remove special symbols and extra spaces and replace with underscore using the replace method
Your regular expression [^a-zA-Z0-9]\s/g
says match any character that is not a number or letter followed by a space.
Remove the \s and you should get what you are after if you want a _ for every special character.
var newString = str.replace(/[^A-Z0-9]/ig, "_");
That will result in hello_world___hello_universe
If you want it to be single underscores use a + to match multiple
var newString = str.replace(/[^A-Z0-9]+/ig, "_");
That will result in hello_world_hello_universe
Related Topics
How to Shut Down a Spring Boot Command-Line Application
Statefulbeantocsv With Column Headers
Parsing the Nested Json Array Using Jackson Library in Java
Cannot Get Jedis Connection; Could Not Get a Resource from the Pool
Password Encrypt and Decrypt Using Spring-Security
How to Get My Loops to Display Horizontally Instead of Vertically
How to Accept Only Numeric Values in a Jtextfield
Hibernate Error - Querysyntaxexception: Users Is Not Mapped [From Users]
Turning Sonar Off for Certain Code
Replacement for Wsimport With Jdk 11
Convert Html/Mxml File to Word Doc Programmatically in Java
Org.Hibernate.Annotationexception: @Onetoone or @Manytoone on <Entity> References an Unknown Entity
How to Indicate to Spring Boot to Use Utc Time Zone for Date Parameters
How to Pass Bundle With Arraylist from Fragment to Activity
Method Does Not Override Method from Its Superclass . Android Fragment
How to Check Hikaricp Connection Pooling Is Working or Not in Java