This question already has answers here:
How do I handle newlines in JSON?
(10 answers)
Closed 4 years ago.
So I have a string:
var s = "foo\nbar\nbob";
I want the string to become:
"foo\\nbar\\nbob"
How can I replace every \n with a \\n?
I've tried using some for loops, but I can't figure it out.
A simple .replace would work - search for \n, and replace with \\n:
var s = "foo\nbar\nbob";
console.log(
s.replace(/\n/g, '\\\n')
// ^^ double backslash needed to indicate single literal backslash
);
Note that this results in "a single backslash character, followed by a literal newline character" - there will not be two backslashes in a row in the actual string. It might be a bit less confusing to use String.raw, which will interpret every character in the template literal literally:
var s = "foo\nbar\nbob";
console.log(
s.replace(/\n/g, String.raw`\
`) // template literal contains one backslash, followed by one newline
);
Related
This question already has answers here:
How can I use backslashes (\) in a string?
(4 answers)
Closed 2 years ago.
console.log('\d' === 'd'); // true
Character 'd' is not a special character, why javascript want to slice the escape notation.
It's better to keep the escape notation in my view.
When I want to fully match string-'\d' using regular expression, it just impossible!
Taking the following code as an example.
console.log(RE.test('\d')); // it should log true
console.log(RE.test('d')); // it should log false
Unfortunately, you just cannot figure out a regular expression pattern.
You have no reason to escape d in a string and JavaScript ignores it. If you need \d you need to escape the escape character: \\d.
See also Why do linters pick on useless escape character?
\d has a special meaning in regular expressions (a digit character), but also in strings (escaped 'd' character, which is exactly like 'd').
Any / creates an escape sequence in a string. Some are "useful" (\n === new line) and some arguably useless (`'\d' === 'd').
If you want the regex \d, you could
1 - use a regex literal instead : /\d/
2 - escape the \ in the string : '\\d', so that the string containing the two characters \ and d is correctly understood by Javascript.
This question already has answers here:
JavaScript backslash (\) in variables is causing an error
(5 answers)
Escaping backslash in string - javascript
(5 answers)
Closed 3 years ago.
I want all single backslashes to be converted into double backslash
"C:\Users\MyName\ringtone.mp3" --> "C:\\Users\\MyName\\ringtone.mp3"
But for some reason it returns "C:UsersMyNameingtone.mp3"
So far I have tried the escape() function and the encodeURI() function but they don't work either. Partial of the string comes from nodejs OS Module which only returns with a single backslash on windows (homedir() function).
Here is what I have so far in the function
function normalize(path: string): string {
return path.normalize().replace(/\\/g, '\\');
}
Thanks in Advance
This should work:
var original = 'C:\\Users\\MyName\\ringtone.mp3';
var replaced = original.normalize().replace(/\\/g, '\\\\');
console.log('Original: ' + original);
console.log('Replaced: ' + replaced);
From what I see you had 2 problems:
First, it seems you were initializing your string like this:
var original = 'C:\Users\MyName\ringtone.mp3'
This would make your actual string value C:UsersMyNameingtone.mp3 because a \ character in javascript symbolizes an escape character.
Second, is because the \ character is an escape character, so the '\\' in your replace function is only looking to replace the matching pattern with a single backslash.
This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
Here is an attempt to remove any excessive blank lines in string.
I'm trying to understand why second approach doesn't workfor lines which contains whitespace.
Demo.
var string = `
foo
bar (there are whitespaced lines between bar and baz. I replaced them with dots)
....................
.......................
...........
baz
`;
// It works
string = string.replace(/^(\s*\n){2,}/gm, '\n');
// Why it doesn't work?
var EOL = string.match(/\r\n/gm) ? '\r\n' : '\n';
var regExp = new RegExp('^(\s*' + EOL + '){2,}', 'gm');
string = string.replace(regExp, EOL);
alert(string);
Your \s needs to be changed to \\s. Just putting \s is the same as s.
In strings (enclosed in quotes), the backslash has a special meaning. For example, \n is the newline character. There are a couple of others that you may or may not have heard of, e.g. \b, \t, \v. It would be bad language design choice to make only a few defined ones special, and consider the non-existent \s to be an actual backslash and an s, because it would be inconsistent, a source of errors, and not future-proof. That's why, when you want to have a backslash in a string, you escape the backslash to \\.
In your first example, you use / characters to delimit the regular expression. This is not considered a string bound by the above rules.
This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 7 years ago.
I am getting long string with multiple occurances of pattern './.'. The string has dates as well in a format of dd.mm.yyyy.
First I tried with javascript replace method as:
str.replace('./.', ''). But it replaced only first occurance of './.'
Then I tried another regex which replaces special characters but it didn't work as it replaced '.' within dates as well.
How do I replace multiple occurances of a pattern './.' without affecting any other characters of a string ?
. is a special character in a regexp, it matches any character, you have to escape it.
str.replace(/\.\/\./g, '');
Use this simple pattern:
/\.\/\./g
to find all "./." strings in your text.
Try it :
str.replace(/\.\/\./g, '');
Escape . and d \
Add a g for global
Like this
str = str.replace(/\./\./g, '');
This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Extra backslash needed in PHP regexp pattern
(4 answers)
Regex to replace single backslashes, excluding those followed by certain chars
(3 answers)
Closed 7 years ago.
function trim(str) {
var trimer = new RegExp("(^[\\s\\t\\xa0\\u3000]+)|([\\u3000\\xa0\\s\\t]+\x24)", "g");
return String(str).replace(trimer, "");
}
why have two '\' before 's' and 't'?
and what's this "[\s\t\xa0\u3000]" mean?
You're using a literal string.
In a literal string, the \ character is used to escape some other chars, for example \n (a new line) or \" (a double quote), and it must be escaped itself as \\. So when you want your string to have \s, you must write \\s in your string literal.
Thankfully JavaScript provides a better solution, Regular expression literals:
var trimer = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+\x24)/g
why have two '\' before 's' and 't'?
In regex the \ is an escape which tells regex that a special character follows. Because you are using it in a string literal you need to escape the \ with \.
and what's this "[\s\t\xa0\u3000]" mean?
It means to match one of the following characters:
\s white space.
\t tab character.
\xa0 non breaking space.
\u3000 wide space.
This function is inefficient because each time it is called it is converting a string to a regex and then it is compiling that regex. It would be more efficient to use a Regex literal not a string and compile the regex outside the function like the following:
var trimRegex = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g;
function trim(str) {
return String(str).replace(trimRegex, "");
}
Further to this \s will match any whitespace which includes tabs, the wide space and the non breaking space so you could simplify the regex to the following:
var trimRegex = /(^\s+)|(\s+$)/g;
Browsers now implement a trim function so you can use this and use a polyfill for older browsers. See this Answer