javascript 将 \/或/\ 替换为单斜杠/ [英] javascript replace \/ or /\ to single slash /

查看:60
本文介绍了javascript 将 \/或/\ 替换为单斜杠/的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于 javascript 中字符串替换的答案,但我找不到 \/到/的答案.请帮我解决这个问题,或者给我发送一些关于如何编写正则表达式的链接,以便替换.谢谢

I know alot of answers are out there for string replace in javascript, but I can't find one for \/ to /. please help me out on this or send me some link to how to write regular expressions in so to replace. Thank you

推荐答案

因为 反斜杠用作转义符,您需要对其进行转义:

Because a backslash is used as an escape character, you'll need to escape it:

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

以上将\/ 替换为/.通常,在字符串中使用反斜杠的任何地方,都可能需要对其进行转义.因此,要将 /\ 替换为 /,您可以使用:

The above replaces \/ with /. In general, anywhere you use a backslash in a string, you probably need to escape it. So, to replace /\ with /, you'd use:

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

当然,这些只会替换字符串中的一个实例.要替换多个实例,请使用带有 g(全局)修饰符的正则表达式:

These will, of course, only replace one instance in the string. To replace multiple instances, use a regular expression with the g (global) modifier:

str = str.replace(/\\\/|\/\\/g, "/")

在这里,因为正斜杠作为正则表达式终止符具有意义,所以您必须避开正斜杠和反斜杠.另一种方法是使用 RegExp 类:

Here, because forward slashes have meaning as regex terminators, you're having to escape the forward slash as well as the backslash. The alternative is to use the RegExp class:

str = str.replace(new RegExp("\\\\/|/\\\\", "g"), "/")

这个中,您必须将反斜杠转义两次——一次在字符串中转义,一次在正则表达式中转义.(这里有一个更好的解释.)

In this one, you're having to escape the backslash twice — once to escape it in the string, and once in the regex. (Here's a better explanation.)

这篇关于javascript 将 \/或/\ 替换为单斜杠/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆