Javascript 替换字符串的第一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2992276/
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-23 02:49:30  来源:igfitidea点击:

Replace first character of string

javascript

提问by MgS

I have a string |0|0|0|0

我有一个字符串 |0|0|0|0

but it needs to be 0|0|0|0

但它必须是 0|0|0|0

How do I replace the first character ('|') with (''). eg replace('|','')

如何将第一个字符 ( '|')替换为( '')。例如 replace('|','')

(with JavaScript)

(使用 JavaScript)

回答by Nick Craver

You can do exactly what you have :)

你可以做你所拥有的:)

var string = "|0|0|0|0";
var newString = string.replace('|','');
alert(newString); // 0|0|0|0

You can see it working here, .replace()in javascript only replaces the first occurrence by default (without /g), so this works to your advantage :)

你可以看到它在这里工作.replace()在 javascript 中默认只替换第一次出现(没有/g),所以这对你有利:)

If you need to check if the first character is a pipe:

如果您需要检查第一个字符是否是管道:

var string = "|0|0|0|0";
var newString = string.indexOf('|') == 0 ? string.substring(1) : string;
alert(newString); // 0|0|0|0?????????????????????????????????????????

You can see the result here

你可以在这里看到结果

回答by Matthew Flaschen

str.replace(/^\|/, "");

This will remove the first character if it's a |.

如果它是 |,这将删除第一个字符。

回答by JSB????

var newstring = oldstring.substring(1);

回答by johnny_bgoode

If you're not sure what the first character will be ( 0 or | ) then the following makes sense:

如果您不确定第一个字符是什么( 0 或 | ),那么以下内容是有意义的:

// CASE 1:
var str = '|0|0|0';
str.indexOf( '|' ) == 0 ? str = str.replace( '|', '' ) : str;
// str == '0|0|0'

// CASE 2:
var str = '0|0|0';
str.indexOf( '|' ) == 0? str = str.replace( '|', '' ) : str;
// str == '0|0|0'

Without the conditional check, str.replace will still remove the first occurrence of '|' even if it is not the first character in the string. This will give you undesired results in the case of CASE 2 ( str will be '00|0' ).

如果没有条件检查,str.replace 仍然会删除第一次出现的 '|' 即使它不是字符串中的第一个字符。在 CASE 2 的情况下,这会给你带来不想要的结果( str 将为 '00|0' )。

回答by Tesserex

It literally is what you suggested.

从字面上看,这就是您所建议的。

"|0|0|0".replace('|', '')

returns "0|0|0"

返回 "0|0|0"

回答by bushman

"|0|0|0|0".split("").reverse().join("")  //can also reverse the string => 0|0|0|0|