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)
To replace the first occurrence of a character in Java, use the replaceFirst() method.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With