Is there a JavaScript regular expression to remove all whitespace except newline? - javascript

How do I remove white spaces in a string but not new line character in JavaScript. I found a solution for C# , by using \t , but it's not supported in JavaScript.
To make it more clear, here's an example:
var s = "this\n is a\n te st"
using regexp method I expect it to return
"this\nisa\ntest"

[^\S\r\n]+
Not a non-whitespace char, not \r and not \n; one or more instances.

This will work, even on \t.
var newstr = s.replace(/ +?/g, '');

Although in Javascript / /g does match \t, I find it can hide the original intent as it reads as a match for the space character. The alternative would be to use a character collection explicitly listing the whitespace characters, excluding \n. i.e. /[ \t\r]+/g.
var newString = s.replace(/[ \t\r]+/g,"");

If you want to match every whitespace character that \s matches except for newlines, you could use this:
/[\t\v\f\r \u00a0\u2000-\u200b\u2028-\u2029\u3000]+/g
Note that this will remove carriage returns (\r), so if the input contains \r\n pairs, they will be converted to just \n. If you want to preserve carriage returns, just remove the \r from the regular expression.

Try this
var trimmedString = orgString.replace(/^\s+|\s+$/g, '') ;

This does the trick:
str.replace(/ /g, "")
and the space does NOT match tabs or linebreaks (CHROME45), no plus or questionmark is needed when replacing globally.
In Perl you have the "horizontal whitespace" shorthand \h to destinguish between linebreaks and spaces but unfortunately not in JavaScript.
The \t shorthand on the other hand IS supported in JavaScript, but it describes the tabulator only.

const str = "abc def ghi";
str.replace(/\s/g, "")
-> "abcdefghi"

try this '/^\\s*/'

code.replace(/^\s[^\S]*/gm, '')
works for me on text like:
#set($todayString = $util.time.nowEpochMilliSeconds())
#set($pk = $util.autoId())
$util.qr($ctx.stash.put("postId", $pk))
and removes the space/tabs before the first 3 lines with removing the spaces in the line.
*optimisation by #Toto:
code.replace(/^\s+/gm, '')

Related

Javascript | Can't replace \n with String.replace()

I have code which parse web-site and take information from database.
It's look like this:
var find = body.match(/\"text\":\"(.*?)\",\"date\"/);
As result, I have:
гороскоп на июль скорпион\nштукатурка на газобетон\nподработка на день\nмицубиси тюмень\nсокращение микрорайон
Then i try to replace \n, but it's don't working.
var str = find[1].replace(new RegExp("\\n",'g'),"*");
What I can do with this?
It looks like you want to replace the text \n, i.e. a backslash followed by an n, as opposed to a newline character.
In which case you can try
var str = find[1].replace(/\\n/g, "*");
or the less readable version
var str = find[1].replace(new RegExp("\\\\n", "g"), "*");
In regular expressions, the string \n matches a newline character. To match a backslash character we need to 'escape' it, by preceding it with another backslash. \\ in a regular expression matches a \ character. Similarly, in JavaScript string literals, \ is the escape character, so we need to escape both backslashes in the regular expression again when we write new RegExp("\\\\n", "g").
Working in the console!
Here this works globally and works on both types of line breaks:
find[1].replace(/\r?\n/g, "*")
if you dont want the '\r' to be replaced you could simply remove that from the regex.
removes all 3 types of line breaks
let s = find[1].replace(/(\r\n|\n|\r)/gm, " - ")

Replace the special character and space from the string in javascript

I have a below string. I need to remove all the special character and space.
var Uid = "s/Information Needed1-s84102-p306";
I tried the below code.It didn't replace the space from the string.
console.log(Uid.replace(/[^\w\s]/gi, '')}")
The output is:- sInformation Needed1s84102p306
I want the output as sInformationNeeded1s84102p306
Simply try using
/[\W_]/g
\W match any non-word character [^a-zA-Z0-9_]
Included _ if you also want to remove it then
Regex
You can just use:
console.log(Uid.replace(/\W+/g, '')}")
\W will match any non-word character including a space.
RegEx Demo
You can use this expression for your case
var x = "s/Information Needed1-s84102-p306";
console(x.replace(/[^A-Z0-9]/ig, ""));
Here is the working Link

Regex replace linebreak and comma

i've a question about regex, i've a text and it looks like below :
car,model,serie
,Mercedes,324,1,
,BMW,23423,1,
,OPEL,54322,1,
it should look like:
car,model,serie
Mercedes,324,1,
BMW,23423,1,
OPEL,54322,1,
so without commas at the beginning of the text.
What i tried :
var str2 = str.replace(/\n|\r/g, "");
but somehow, i couldn't add comma in regex.
can anyone help me?
Thanks in advance.
There have been a lot of responses to this question and for a newbie to regex it is probably a bit overwelming,
Overall the best response has been:
var str2 = str.replace(/^,/gm, '');
This works by using ^, to check if the first character is a comma and if it is, remove it. It also uses the g and m flags to do this for the first character of every line.
If you are curious about the other versions then read on:
1:
var str2 = str.replace(/^,+/gm, '');
This is a slight variant in that it will remove multiple consecutive commas at the beginning of each line, but based off of your dataset this is not required.
2:
var str2 = str.replace(/\n,/g, '\n');
This version works exactly the same as the first, however it finds each newline follow by a comma with \n, and replaces it with another newline.
3:
var str2 = str.replace(/(\n|\r),/g, '$1')
This version is the same as the previous however it doesn't make the assumption that the newline is a \n, it instead captures any newlines or carriage returns, it works the same as the m flag and ^,.
4:
var str2 = str.replace(/\n+|\r+|,+/g,"\n")
And finally there is this, this is a combination of all the previous regex's, it makes the assumption that you may have a lot mixed newlines and commas without any text, and that you would want to remove all of those characters, it is unnecessary for your examples.
Use this syntax:
str.replace(/^,/gm, '');
You can just use multiline flag and replace leading commas:
str = str.replace(/^,+/gm);
RegEx Demo
Try:
var str2 = str.replace(/(\n|\r),/g, '$1')
Your comma was actually placed outside the regex pattern, so you weren't far off :)

Regex for both newline and backslash for Replace function

I am using a replace function to escape some characters (both newline and backslash) from a string.
Here is my code:
var str = strElement.replace(/\\/\n/g, "");
I am trying to use regex, so that I can add more special characters if needed. Is this a valid regex or can someone tell me what am I doing wrong here?
You're ending the regex early with an unescaped forward slash. You also want to use a set to match individual characters. Additionally you might want to add "\r" (carriage return) in as well as "\n" (new line).
This should work:
var str = strElement.replace(/[\\\n\r]/g, "");
This is not a valid regex as the slash is a delimiter and ends the regex. What you probably wanted is the pipe (|), which is an alternation:
var str = strElement.replace(/\\|\n/g, "");
In case you need to extend it in the future it may be helpful to use a character class to improve readability:
var str = strElement.replace(/[\\\nabcx]/g, "");
A character class matches a single character from it's body.
This should work. The regular expression replaces both the newline characters and the backslashes in escaped html text:
var str = strElement.replace(/\\n|\\r|\\/g, '');

Replace all whitespace characters

I want to replace all occurrences of white space characters (space, tab, newline) in JavaScript.
How to do so?
I tried:
str.replace(/ /gi, "X")
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");
We can also use this if we want to change all multiple joined blank spaces with a single character:
str.replace(/\s+/g,'X');
See it in action here: https://regex101.com/r/d9d53G/1
Explanation
/ \s+ / g
\s+ matches any whitespace character (equal to [\r\n\t\f\v ])
+ Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
Global pattern flags
g modifier: global. All matches (don't return after first match)
\s is a meta character that covers all white space. You don't need to make it case-insensitive — white space doesn't have case.
str.replace(/\s/g, "X")
Have you tried the \s?
str.replace(/\s/g, "X");
If you use
str.replace(/\s/g, "");
it replaces all whitespaces. For example:
var str = "hello my world";
str.replace(/\s/g, "") //the result will be "hellomyworld"
Try this:
str.replace(/\s/g, "X")
Not /gi but /g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
gives
"My_Family_File.jpg"
You could use the function trim
let str = ' Hello World ';
alert (str.trim());
All the front and back spaces around Hello World would be removed.
Actually it has been worked but
just try this.
take the value /\s/g into a string variable like
String a = /\s/g;
str = str.replaceAll(a,"X");
I've used the "slugify" method from underscore.string and it worked like a charm:
https://github.com/epeli/underscore.string#slugifystring--string
The cool thing is that you can really just import this method, don't need to import the entire library.

Categories

Resources