Javascript 和反斜杠替换

发布于 2024-08-25 15:08:42 字数 279 浏览 7 评论 0原文

这是我的字符串:

var str = "This is my \string";

这是我的代码:

var replaced = str.replace("/\\/", "\\\\");

我无法得到我的输出:

"This is my \\string"

我已经尝试了我能想到的正则表达式和替换值的每种组合。

任何帮助表示赞赏!

here is my string:

var str = "This is my \string";

This is my code:

var replaced = str.replace("/\\/", "\\\\");

I can't get my output to be:

"This is my \\string"

I have tried every combination I can think of for the regular expression and the replacement value.

Any help is appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

物价感观 2024-09-01 15:08:42

被这个问题困扰了很长时间,所有的答案都坚持认为源字符串需要已经转义了反斜杠......但情况并非总是如此。

这样做..

var replaced = str.replace(String.fromCharCode(92),String.fromCharCode(92,92));

Got stumped by this for ages and all the answers kept insisting that the source string needs to already have escaped backslashes in it ... which isn't always the case.

Do this ..

var replaced = str.replace(String.fromCharCode(92),String.fromCharCode(92,92));
爺獨霸怡葒院 2024-09-01 15:08:42

该字符串不包含反斜杠,它包含 \s 转义序列。

var str = "This is my \\string";

如果你想要一个正则表达式,你应该有一个正则表达式,而不是一个字符串。

var replaced = str.replace(/\\/, "\\\\");

The string doesn't contain a backslash, it contains the \s escape sequence.

var str = "This is my \\string";

And if you want a regular expression, you should have a regular expression, not a string.

var replaced = str.replace(/\\/, "\\\\");
回眸一笑 2024-09-01 15:08:42

问题是第一行中的 \ 甚至无法识别。它认为反斜杠将标记转义序列,但 \s 不是转义字符,因此它被忽略。您的 var str 被解释为“这是我的字符串”。尝试 str.indexOf("\\") - 你会发现它是 -1,因为根本没有反斜杠。如果您控制 str 的内容,请按照 David 所说的操作 - 添加另一个 \ 来转义第一个。

The problem is that the \ in your first line isn't even recognized. It thinks the backslash is going to mark an escape sequence, but \s isn't an escape character, so it's ignored. Your var str is interpreted as just "This is my string". Try str.indexOf("\\") - you'll find it's -1, since there is no backslash at all. If you control the content of str, do what David says - add another \ to escape the first.

再见回来 2024-09-01 15:08:42
var a = String.raw`This is my \string`.replace(/\\/g,"\\\\");
console.log(a);

结果:

This is my \\string

var a = String.raw`This is my \string`.replace(/\\/g,"\\\\");
console.log(a);

Result:

This is my \\string
此岸叶落 2024-09-01 15:08:42

如果您有多个实例或反斜杠:

str.split(String.fromCharCode(92)).join(String.fromCharCode(92,92))

In case you have multiple instances or the backslash:

str.split(String.fromCharCode(92)).join(String.fromCharCode(92,92))
我家小可爱 2024-09-01 15:08:42

使用这个

str.replace(/(\s)/g,function($0){return $0==' '?' ':'\\s'})

str.replace(/ /g,'something').replace(/\s/g,'\\s').replace(/something/g,' ');

“某事”它可能是字符串中不存在的字符的组合

var str=' \s';  
  str.replace(/\s/g,'\\s'); 
// return '\\s\\s'   
  str.replace(/ /g,'SpAcE').replace(/\s/g,'\\s').replace(/SpAcE/g,' ');
// return ' \\s' 

Use this

str.replace(/(\s)/g,function($0){return $0==' '?' ':'\\s'})

or

str.replace(/ /g,'something').replace(/\s/g,'\\s').replace(/something/g,' ');

'something' it may be a combination of characters that is not in string

var str=' \s';  
  str.replace(/\s/g,'\\s'); 
// return '\\s\\s'   
  str.replace(/ /g,'SpAcE').replace(/\s/g,'\\s').replace(/SpAcE/g,' ');
// return ' \\s' 
娇柔作态 2024-09-01 15:08:42

我认为混乱来自于字符串在浏览器控制台中的显示方式。 (我刚刚检查了 chrome)

let myString = "This is my \string";

这里 myString 实际上不包含任何反斜杠字符。它包括解析为 s\s 序列。

所以如果你在控制台中显示你的字符串:

> myString => 
"This is my string"

> console.log(myString) 
This is my string

下面的字符串虽然只有 1 个反斜杠:

let myString = "This is my \\string";


//string representation includes the escape char as well. So we see double backslashes.  
> myString => 
"This is my \\string" 

//When you print it, the escape char is not there. 
> console.log(myString) 
This is my \string 

所以最后如果你想用 2 个反斜杠替换反斜杠字符,你可以这样做:

let myNewStringWith2Backslashes= myString.replace("\\","\\\\")

I think the confusion is coming from how a string is displayed in the browser console. (I just checked chrome)

let myString = "This is my \string";

Here myString is actually doesn't include any backslash char. It includes \s sequence which resolves to s.

So If you display your string in the console:

> myString => 
"This is my string"

> console.log(myString) 
This is my string

The following string though has only 1 backslash in it:

let myString = "This is my \\string";


//string representation includes the escape char as well. So we see double backslashes.  
> myString => 
"This is my \\string" 

//When you print it, the escape char is not there. 
> console.log(myString) 
This is my \string 

So finally if you want to replace backslash char with 2 backslashes you can do this:

let myNewStringWith2Backslashes= myString.replace("\\","\\\\")
月亮坠入山谷 2024-09-01 15:08:42

如果用例是替换函数的 toString 中的某些值,并将字符串转换回有效的函数。

var exFnStr1 = exFn.toString();

var exFnStr = "";
var quoteStarted = false;
for(i = 0; i < exFnStr1.length; i++) {
    var iChar = exFnStr1.charAt(i);
    var oChar = exFnStr1.charAt(i);
    var currentCharCode = exFnStr1.charCodeAt(i);
    if(quoteStarted) {
        if(currentCharCode === 9) oChar = "tabChar";
        if(currentCharCode === 10) oChar = "newlineChar";
    }
    //console.log(iChar+"->"+currentCharCode+"->"+oChar)
    exFnStr += oChar;

    if(currentCharCode === 34) {
        if(quoteStarted) quoteStarted = false;
        else quoteStarted = true;
    }
}
console.log(exFnStr);

//TODO - replace values in the string

exFn = new Function('return ' + exFnStr)();

If use case is to replace some values in the toString of a function, and convert the string back to a valid function.

var exFnStr1 = exFn.toString();

var exFnStr = "";
var quoteStarted = false;
for(i = 0; i < exFnStr1.length; i++) {
    var iChar = exFnStr1.charAt(i);
    var oChar = exFnStr1.charAt(i);
    var currentCharCode = exFnStr1.charCodeAt(i);
    if(quoteStarted) {
        if(currentCharCode === 9) oChar = "tabChar";
        if(currentCharCode === 10) oChar = "newlineChar";
    }
    //console.log(iChar+"->"+currentCharCode+"->"+oChar)
    exFnStr += oChar;

    if(currentCharCode === 34) {
        if(quoteStarted) quoteStarted = false;
        else quoteStarted = true;
    }
}
console.log(exFnStr);

//TODO - replace values in the string

exFn = new Function('return ' + exFnStr)();
忘年祭陌 2024-09-01 15:08:42

我还没有尝试过这个,但是下面的应该可以工作

var replaced = str.replace((new RegExp("\s"),"\\s");

本质上你不想替换“\”,你想替换由“\s”转义序列表示的字符。

不幸的是,您需要对字母表中的每个字母、每个数字、符号等执行此操作,才能覆盖所有基础

I haven't tried this, but the following should work

var replaced = str.replace((new RegExp("\s"),"\\s");

Essentially you don't want to replace "\", you want to replace the character represented by the "\s" escape sequence.

Unfortunately you're going to need to do this for every letter of the alphabet, every number, symbol, etc in order to cover all bases

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文