How to replace a single backslash with regular in js
大家讲道理
大家讲道理 2017-06-12 09:31:16
0
3
1011
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?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(3)
学习ing

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!

三叔

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_u1582

What kind of scenario do you want to use it for? I don’t know if this situation is the result you want:

  1. Create test.txt, the content is aa\a/b

  2. 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template