删除Javascript中字符串的第一个字符

时间:2022-12-19 20:29:41

I want to delete the first character of a string, if the first character is a 0. The 0 can be there more than once.

我想删除字符串的第一个字符,如果第一个字符是0。0可以不止一次。

Is there a simple function that checks the first character and deletes it if it is 0?

是否有一个简单的函数检查第一个字符并在它为0时删除它?

Right now, I'm trying it with the JS slice() function but it is very awkward.

现在,我正在用JS slice()函数尝试它,但是它非常笨拙。

12 个解决方案

#1


394  

var s = "0000test";
while(s.charAt(0) === '0')
{
 s = s.substr(1);
}

This will kill any 0's at the start of the string.

这将在字符串的开始处杀死所有的0。

#2


71  

Use .charAt() and .slice().

使用.charAt()和.slice()。

Example: http://jsfiddle.net/kCpNQ/

例如:http://jsfiddle.net/kCpNQ/

var myString = "0String";

if( myString.charAt( 0 ) === '0' )
    myString = myString.slice( 1 );

If there could be several 0 characters at the beginning, you can change the if() to a while().

如果开头可能有几个0字符,可以将If()改为while()。

Example: http://jsfiddle.net/kCpNQ/1/

例如:http://jsfiddle.net/kCpNQ/1/

var myString = "0000String";

while( myString.charAt( 0 ) === '0' )
    myString = myString.slice( 1 );

#3


66  

Very readable code is to use .substring() with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring() method is actually optional, so you don't even need to call .length()...

非常可读的代码是使用.substring(),并将其设置为第二个字符(1)的索引(第一个字符的索引为0)。

TL;DR : Remove first character from the string:

str = str.substring(1);

...yes it is that simple...

…是的,就是这么简单……

Removing some particular character(s):

As @Shaded suggested, just loop this while first character of your string is the "unwanted" character...

正如@阴影所建议的那样,在字符串的第一个字符是“不需要的”字符时,只需循环该字符…

var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substr(1);
//yourString now contains "test"

.slice() vs .substring() vs .substr()

Quote from (and more on that in) What is the difference between String.slice and String.substring?

引用(以及更多)字符串之间的区别。片和String.substring吗?

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn´t.

他还指出,如果要切片的参数是负的,那么它们将从末尾引用字符串。子字符串的子串并´t。

#4


47  

The easiest way to strip all leading 0s is:

最简单的方法就是:

var s = "00test";
s = s.replace(/^0+/, "");

If just stripping a single leading 0 character, as the question implies, you could use

如果像问题所暗示的那样,仅仅去掉一个前导0字符,您可以使用

s = s.replace(/^0/, "");

#5


13  

Did you try the substring function?

你试过子字符串函数吗?

string = string.indexOf(0) == '0' ? string.substring(1) : string;

Here's a reference - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring

这里有一个引用—https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring

And you can always do this for multiple 0s:

对于多个0都可以这样做:

while(string.indexOf(0) == '0')
{
    string = string.substring(1);
}

#6


6  

var s = "0test";
if(s.substr(0,1) == "0") {
    s = s.substr(1);
}

For all 0s: http://jsfiddle.net/An4MY/

对于所有0:http://jsfiddle.net/An4MY/

String.prototype.ltrim0 = function() {
 return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();

#7


4  

//---- remove first and last char of str    
str = str.substring(1,((keyw.length)-1));

//---- remove only first char    
str = str.substring(1,(keyw.length));

//---- remove only last char    
str = str.substring(0,(keyw.length));

#8


3  

Here's one that doesn't assume the input is a string, uses substring, and comes with a couple of unit tests:

这里有一个不假设输入是字符串,使用子字符串,并附带几个单元测试:

var cutOutZero = function(value) {
    if (value.length && value.length > 0 && value[0] === '0') {
        return value.substring(1);
    }

    return value;
};

http://jsfiddle.net/TRU66/1/

http://jsfiddle.net/TRU66/1/

#9


2  

This may be a bit of overkill but hey I was bored.

这可能有点过头了,但嘿,我很无聊。

String.prototype.deleteAt = function (index, predicate) {
    var c = this[+index];
    if (!predicate || predicate(c)) {
        var before = this.substring(0, Math.max(index - 1, 0));
        var after = this.substring(Math.min(index + 1, this.length - 1));
        return before + after;
    }
    return this;
}

var str = "0ABC";
var newStr = str.deleteAt(0, function (c) { 
    return c === '0'; 
});

This version may be of more use to you though.

这个版本可能对您更有用。

String.prototype.trimStartWhile = function (predicate) {
    if (typeof predicate !== "function") {
        return this;
    }
    var str = this;
    while (str.length > 0 && predicate(this[0])) {
        str = str.substring(1);
    }
    return str;
}

var str = "0ABC";
var newStr = str.trimStartWhile(function (c) { 
    return c === '0'; 
});

#10


1  

How about

如何

let a = "My test string";

a = a.substring(1, a.length);

console.log(a); // y test string

#11


0  

var test = '0test';
test = test.replace(/0(.*)/, '$1');

#12


0  

From the Javascript implementation of trim() > that removes and leading or ending spaces from strings. Here is an altered implementation of the answer for this question.

从trim() >的Javascript实现中删除、引导或结束字符串中的空格。这里是对这个问题的答案的改变的实现。

var str = "0000one two three0000"; //TEST  
str = str.replace(/^\s+|\s+$/g,'0'); //ANSWER

Original implementation for this on JS

这是JS上的原始实现

string.trim():
if (!String.prototype.trim) {
 String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,'');
 }
}

#1


394  

var s = "0000test";
while(s.charAt(0) === '0')
{
 s = s.substr(1);
}

This will kill any 0's at the start of the string.

这将在字符串的开始处杀死所有的0。

#2


71  

Use .charAt() and .slice().

使用.charAt()和.slice()。

Example: http://jsfiddle.net/kCpNQ/

例如:http://jsfiddle.net/kCpNQ/

var myString = "0String";

if( myString.charAt( 0 ) === '0' )
    myString = myString.slice( 1 );

If there could be several 0 characters at the beginning, you can change the if() to a while().

如果开头可能有几个0字符,可以将If()改为while()。

Example: http://jsfiddle.net/kCpNQ/1/

例如:http://jsfiddle.net/kCpNQ/1/

var myString = "0000String";

while( myString.charAt( 0 ) === '0' )
    myString = myString.slice( 1 );

#3


66  

Very readable code is to use .substring() with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring() method is actually optional, so you don't even need to call .length()...

非常可读的代码是使用.substring(),并将其设置为第二个字符(1)的索引(第一个字符的索引为0)。

TL;DR : Remove first character from the string:

str = str.substring(1);

...yes it is that simple...

…是的,就是这么简单……

Removing some particular character(s):

As @Shaded suggested, just loop this while first character of your string is the "unwanted" character...

正如@阴影所建议的那样,在字符串的第一个字符是“不需要的”字符时,只需循环该字符…

var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substr(1);
//yourString now contains "test"

.slice() vs .substring() vs .substr()

Quote from (and more on that in) What is the difference between String.slice and String.substring?

引用(以及更多)字符串之间的区别。片和String.substring吗?

He also points out that if the parameters to slice are negative, they reference the string from the end. Substring and substr doesn´t.

他还指出,如果要切片的参数是负的,那么它们将从末尾引用字符串。子字符串的子串并´t。

#4


47  

The easiest way to strip all leading 0s is:

最简单的方法就是:

var s = "00test";
s = s.replace(/^0+/, "");

If just stripping a single leading 0 character, as the question implies, you could use

如果像问题所暗示的那样,仅仅去掉一个前导0字符,您可以使用

s = s.replace(/^0/, "");

#5


13  

Did you try the substring function?

你试过子字符串函数吗?

string = string.indexOf(0) == '0' ? string.substring(1) : string;

Here's a reference - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring

这里有一个引用—https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring

And you can always do this for multiple 0s:

对于多个0都可以这样做:

while(string.indexOf(0) == '0')
{
    string = string.substring(1);
}

#6


6  

var s = "0test";
if(s.substr(0,1) == "0") {
    s = s.substr(1);
}

For all 0s: http://jsfiddle.net/An4MY/

对于所有0:http://jsfiddle.net/An4MY/

String.prototype.ltrim0 = function() {
 return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();

#7


4  

//---- remove first and last char of str    
str = str.substring(1,((keyw.length)-1));

//---- remove only first char    
str = str.substring(1,(keyw.length));

//---- remove only last char    
str = str.substring(0,(keyw.length));

#8


3  

Here's one that doesn't assume the input is a string, uses substring, and comes with a couple of unit tests:

这里有一个不假设输入是字符串,使用子字符串,并附带几个单元测试:

var cutOutZero = function(value) {
    if (value.length && value.length > 0 && value[0] === '0') {
        return value.substring(1);
    }

    return value;
};

http://jsfiddle.net/TRU66/1/

http://jsfiddle.net/TRU66/1/

#9


2  

This may be a bit of overkill but hey I was bored.

这可能有点过头了,但嘿,我很无聊。

String.prototype.deleteAt = function (index, predicate) {
    var c = this[+index];
    if (!predicate || predicate(c)) {
        var before = this.substring(0, Math.max(index - 1, 0));
        var after = this.substring(Math.min(index + 1, this.length - 1));
        return before + after;
    }
    return this;
}

var str = "0ABC";
var newStr = str.deleteAt(0, function (c) { 
    return c === '0'; 
});

This version may be of more use to you though.

这个版本可能对您更有用。

String.prototype.trimStartWhile = function (predicate) {
    if (typeof predicate !== "function") {
        return this;
    }
    var str = this;
    while (str.length > 0 && predicate(this[0])) {
        str = str.substring(1);
    }
    return str;
}

var str = "0ABC";
var newStr = str.trimStartWhile(function (c) { 
    return c === '0'; 
});

#10


1  

How about

如何

let a = "My test string";

a = a.substring(1, a.length);

console.log(a); // y test string

#11


0  

var test = '0test';
test = test.replace(/0(.*)/, '$1');

#12


0  

From the Javascript implementation of trim() > that removes and leading or ending spaces from strings. Here is an altered implementation of the answer for this question.

从trim() >的Javascript实现中删除、引导或结束字符串中的空格。这里是对这个问题的答案的改变的实现。

var str = "0000one two three0000"; //TEST  
str = str.replace(/^\s+|\s+$/g,'0'); //ANSWER

Original implementation for this on JS

这是JS上的原始实现

string.trim():
if (!String.prototype.trim) {
 String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,'');
 }
}