Javascript 从Javascript中的字符串中删除特定字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10396074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:08:44  来源:igfitidea点击:

Remove specific characters from a string in Javascript

javascriptstring

提问by AlphaPapa

I am creating a form to lookup the details of a support request in our call logging system.

我正在创建一个表单,用于在我们的通话记录系统中查找支持请求的详细信息。

Call references are assigned a number like F0123456which is what the user would enter, but the record in the database would be 123456. I have the following code for collecting the data from the form before submitting it with jQueryajax. How would i strip out the leading 'F0' from the string if it exists?

呼叫参考被分配一个数字,就像F0123456用户将输入的数字一样,但数据库中的记录将是123456. 我有以下代码,用于在使用jQueryajax提交表单之前从表单中收集数据。如果存在,我将如何从字符串中去除前导“F0”?

$('#submit').click(function () {        

var rnum = $('input[name=rnum]');
var uname = $('input[name=uname]');

var url = 'rnum=' + rnum.val() + '&uname=' + uname.val();

回答by Mathias Bynens

Simply replace it with nothing:

简单地替换它:

var string = 'F0123456'; // just an example
string.replace(/^F0+/i, ''); '123456'

回答by StormsEngineering

Honestly I think this probably the most concise and least confusing, but maybe that is just me:

老实说,我认为这可能是最简洁和最不容易混淆的,但也许这只是我:

str = "F0123456";
str.replace("f0", "");

Dont even go the regular expression route and simply do a straight replace.

甚至不要走正则表达式路线,只需直接替换即可。

回答by paulslater19

Another way to do it:

另一种方法:

rnum = rnum.split("F0").pop()

rnum = rnum.split("F0").pop()

It splits the string in to two: ["", "123456"], then selects the last element

它将字符串一分为二:["", "123456"],然后选择最后一个元素

回答by Bergi

Regexp solution:

正则表达式解决方案:

ref = ref.replace(/^F0/, "");

plain solution:

简单的解决方案:

if (ref.substr(0, 2) == "F0")
     ref = ref.substr(2);

回答by Eissa Saber

if it is not the first two chars and you wanna remove F0 from the whole string then you gotta use this regex

如果它不是前两个字符并且你想从整个字符串中删除 F0 那么你必须使用这个正则表达式

   let string = 'F0123F0456F0';
   let result = string.replace(/F0/ig, '');
   console.log(result);