var a="a\a\a/b"
var reg=/\/g;
alert(a.replace(reg,"-"));
The final output result of my code is aa-a/b
The regex only replaces double backslashes, but not single backslashes. How can I modify it to replace it?
The reason is because \ is used as an escape character. You can see in the chrome console that the final output of "aa\a/b" is "aaa/b"
How to solve this situation?
学习ing2017-06-12 09:33:16
The backslash "" is an escape character. It appears in front of a character and represents a whole. For example, "n" represents a newline character. See the code below:
var str = '\fedlab';
console.log(str.length); // 6
In other words, "f" counts as one character.
console.log(/^\fedlab/.test('\fedlab')); // true
Hope this helps!
三叔2017-06-12 09:33:16
I checked the information and found no solution. It is regarded as an escape character, which is a low-level implementation and cannot be searched and replaced. The characters still have to be written as "a\a\\a/b"
phpcn_u15822017-06-12 09:33:16
What kind of scenario do you want to use it for? I don’t know if this situation is the result you want:
Create test.txt
, the content is aa\a/b
Create test.js
, and perform some tests and results on the node console below:
//test.js
'use strict';
var fs=require('fs')
var a=fs.readFileSync(__dirname+'/test.txt').toString()
var b='a\a\\a/b'
console.log(a.length) //=>8 如果不是8,可能是加入了一些空格或换行符
console.log(a==b) //=>true
console.log(a.replace(/\/g,'-')) //=>a-a--a/b
Then I think it makes no sense to replace var a="aa\a/b"
the backslash of this string
. You may have confused string
and text character