Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace first character of string

Tags:

javascript

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

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

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

(with JavaScript)

like image 1000
MgS Avatar asked Jun 07 '10 19:06

MgS


People also ask

How do you replace the first character of a string in Java?

To replace the first occurrence of a character in Java, use the replaceFirst() method.

How do you replace the first two characters of a string?

To replace the first N characters in a string, use the slice() method, passing it the number of characters you want to replace as a parameter and prepend the replacement string using the addition (+) operator. Copied! We used the String.

How do you replace the first character of a string in Python?

Use Python built-in replace() function to replace the first character in the string. The str. replace takes 3 parameters old, new, and count (optional). Where count indicates the number of times you want to replace the old substring with the new substring.

How do you replace a specific character in a string?

Using 'str.replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


1 Answers

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 :)

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

like image 126
Nick Craver Avatar answered Sep 21 '22 17:09

Nick Craver