简体   繁体   English

如何从字符串中间删除反斜杠

[英]How to remove Backslash from the middle of a string

The usernames used by my organization are in the following format: 我的组织使用的用户名采用以下格式:

i:4#.w|abcd\\1231231234.abc 我:4#.W | ABCD \\ 1231231234.abc

I need to remove the \\ and everything before it using JavaScript. 我需要在使用JavaScript之前删除\\及其所有内容。 I have the following code but because of the escape function of the \\ in JS I find that JS simply remove \\13 from the string. 我有以下代码,但是由于JS中\\的转义功能,我发现JS只是从字符串中删除\\ 13。 I have search for hours and haven't been able to find any solution. 我已经搜索了几个小时,却找不到任何解决方案。 Here is the current code. 这是当前代码。

<script type="text/javascript">
   window.onload = function () {
       document.getElementById('userId').innerHTML ="i:4#.w|abmy\1391251254.abc";
   }
</script>

<div>
    <span id="userId"></span>
</div>

I need the result to be 1391251254.abc 我需要的结果是1391251254.abc

You can use a regex to extract the last part of your string. 您可以使用正则表达式提取字符串的最后一部分。 It will work event if the string contains more than one backslash. 如果字符串包含多个反斜杠,它将起作用。

 var string = "i:4#.w|abmy\\\\1391251254.abc"; //Note the escaped '\\' var regex = /.*?\\\\(.*)$/; var match = regex.exec(string); console.log(match[1]); //1391251254.abc 

An alternative is using the function substring along with the function lastIndexOf . 一种替代方法是将函数substring与函数lastIndexOf一起使用。

var str = "i:4#.w|abmy\\1391251254.abc"
str = str.substring(str.lastIndexOf('\\') + 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM