最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to remove forward and backward slashes from string in javascript - Stack Overflow

programmeradmin3浏览0评论

I want to remove all the forward and backward slash characters from the string using the Javascript.

Here is what I have tried:

var str = "//hcandna\\"
str.replace(/\\/g,'');

I also tried using str.replace(/\\///g,''), but I am not able to do it.

How can I do it?

I want to remove all the forward and backward slash characters from the string using the Javascript.

Here is what I have tried:

var str = "//hcandna\\"
str.replace(/\\/g,'');

I also tried using str.replace(/\\///g,''), but I am not able to do it.

How can I do it?

Share Improve this question edited Aug 30, 2018 at 15:51 Nimeshka Srimal 8,9305 gold badges45 silver badges60 bronze badges asked Aug 30, 2018 at 11:54 CeejayCeejay 7,26719 gold badges65 silver badges109 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 16

You can just replace \/ or (|) \\ to remove all occurrences:

var str = "//hcandna\\"
console.log( str.replace(/\\|\//g,'') );

Little side note about escaping in your RegEx:

A slash \ in front of a reserved character, is to escape it from it's function and just represent it as a char. That's why your approach \\// did not make sense. You escapes \ with \, so it becomes \\. But if you want to escape /, you need to do it like this too: \/.

You want something more like this:

var str = "//hcandna\\"
str=str.replace(/[\/\\]/g,'');
console.log(str);

This will search for the set of characters containing a forward or backward slash and replace them globally. What you had requires a backslash followed by a forward slash.

Here's the output from Node:

  str.replace(/[\/\\]/g,'')
  'hcandna'

You need to add the result to a new string like:

var newstr = str.replace(/(\\|\/)+/ig, '');

You can use this code snippet

str.replace(/(\\|\/)/g,'');
发布评论

评论列表(0)

  1. 暂无评论