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

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, " - ")

Related

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, '');

how to replace backslash character with double backslash in javascript?

I'm trying to replace backslashes in my string with two backslashes like so:
s = s.replace("\\", "\\\\");
But, it doesn't do anything. Example string:
s="\r\nHi\r\n";
The string doesn't contain a backslash, it contains the \r escape sequence.
Working example
For example
var str = "\r\n";
var replaced = str.replace('\r\n', '\\r\\n');
alert(replaced);
Then the alert will be shown \r\n

Replace '\' with '-' in a string

I have seen all the questions asked previously but it didn't help me out . I have a string that contains backslash and i want to replace the backslashes with '-'
var s="adbc\sjhf\fkjfh\af";
s = s.replace(/\\/g,'-');
alert(s);
I thought this is the proper way to do it and of course i am wrong because in alert it shows adbcsjhffkjfhaf but i need it to be like adbc-sjhf-fkjfh-af.
What mistake i do here and what is the reason for it and how to achieve this...??
Working JS Fiddle
Your s is initially adbcsjhffkjfhaf. You meant
var s="adbc\\sjhf\\fkjfh\\af";
You need to double-up the backslashes in your input string:
var s="adbc\\sjhf\\fkjfh\\af";
Prefixing a character with '\' in a string literal gives special meaning to that character (eg '\t' means a tab character). If you want to actually include a '\' in your string you must escape it with a second backslash: '\\'
Javascript is ignoring the \ in \s \f \a in your string. Do a console.log(s) after assigning, you will understand.
You need to escape \ with \\. Like: "adbc\\sjhf\\fkjfh\\af"
The string doesn't contain a backslash, it contains the \a, \s and \f (escape sequence for Form Feed).
if you change your string to adbc\\sjhf\\fkjfh\\af
var s="adbc\\sjhf\\fkjfh\\af";
s = s.replace(/\\/g,'-');
alert(s);
you will be able to replace it with -

unterminated string literal in the variable

var MM = '\' + obj[0]['MM '] + '/';
I get two errors while using this code...
missing; before statement and
unterminated string literal
The character \ is "special" because it's used to allow the use of all printable characters in strings. In your case '\' is not a string composed by the only character \, but the beginning of a string starting with the single quote character '.
For exampe if you want the string Hello Andrea "6502" Griffini you can use single quotes
string1 = 'Hello Andrea "6502" Griffini';
and if you want single quotes in the string you can do the opposite
string2 = "Hello Andrea '6502' Griffini";
But what if you want both kind of quotes in the same string? This is where the escape \ character comes handy:
string3 = "'llo Andrea \"6502\" Griffini";
Basically \ before a quote or double quote in a string tells javascript that the following character is just a regular character, with no special meaning attached to it.
Note that the very same character is also used in regular expressions... for example if you want to look for an open bracket [ you must prefix it with a backslash because [ in a regular expression has a special meaning.
The escape is also used to do the opposite... in a string if you put a backslash in front of a normal character you are telling javascript that that character is indeed special... for example
alert("This is\na test");
In the above line the \n sequence means a newline code, so the message displayed will be on two lines ("This is" and "a test").
You may now wonder... what if I need a backslash character in my string? Just double it in that case. In your code for example just use '\\'.
Here is a table for the possible meanings of backslash in strings
\" just a regular double-quote character, it doesn't end the string
\' just a regular single-quote character, it doesn't end the string
\b a backspace character (ASCII code 0x08)
\t a tab character (ASCII code 0x09)
\n a newline character (ASCII code 0x0A)
\v a vertical tab character (ASCII code 0x0B)
\f a form feed character (ASCII code 0x0C)
\r a carriage return character (ASCII code 0x0D)
\033 the character with ASCII code 033 octal = 27 ("ESC" in this case)
\x41 the character with ASCII code 0x41 = 65 ("A" in this case)
\u05D0 the unicode character 0x05D0 (Aleph from the Hebrew charset)
\\ just regular backslash character, not an escape prefix
\ is an escape character. You'll have to double it to literally mean a backslash character, otherwise it'll augment the following character (In this case the next single quote)
You need to properly escape the backslash:
var lastMenstrualPeriod = '\\' + obj[0]['LastMenstrualPeriod'] + '/';
Being escape character, the JS "compiler" is expecting another character to follow, for example \n is newline constant, \t is tab etc.. so \\ is one single backslash in a string.
It is also mentioned in Douglas Crockford book.
You are forgetting to escape '\'
Do this:
var lastMenstrualPeriod = '\\' + obj[0]['LastMenstrualPeriod'] + '/';

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

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, '')

Categories

Resources