Your s
is initially adbcsjhffkjfhaf
. You meant
var s="adbc\\sjhf\\fkjfh\\af";
题
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...??
解决方案
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 -