简体   繁体   English

替换字符串的第一个字符

[英]Replace first character of string

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)

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 :)您可以在这里看到它的工作原理,javascript 中的.replace()仅替换默认情况下的第一次出现(没有/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你可以在这里看到结果

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

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

var newstring = oldstring.substring(1);

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 '|'如果没有条件检查,str.replace 仍然会删除第一次出现的 '|' 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' ).在 CASE 2 的情况下,这会给你带来不想要的结果( str 将为 '00|0' )。

Try this:尝试这个:

var str = "|0|0|0|0";
str.replace(str.charAt(0), "");

Avoid using substr() as it's considered deprecated .避免使用substr()因为它被认为已弃用

It literally is what you suggested.从字面上看,这就是您所建议的。

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

returns "0|0|0"返回"0|0|0"

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

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

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