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.
Is there a simple function that checks the first character and deletes it if it is 0?
Right now, I'm trying it with the JS slice() function but it is very awkward.
You can remove the first character of a string using substring:
var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"
To remove all 0's at the start of the string:
var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}
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()...
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.substring(1);
//yourString now contains "test"
.slice() vs .substring() vs .substr()
EDIT: substr() is not standardized and should not be used for new JS codes, you may be inclined to use it because of the naming similarity with other languages, e.g. PHP, but even in PHP you should probably use mb_substr() to be safe in modern world :)
Quote from (and more on that in) What is the difference between String.slice and 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.
Use .charAt() and .slice().
Example: 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().
Example: http://jsfiddle.net/kCpNQ/1/
var myString = "0000String";
while( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
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
s = s.replace(/^0/, "");
You can do it with substring method:
let a = "My test string";
a = a.substring(1);
console.log(a); // y test string
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
And you can always do this for multiple 0s:
while(string.indexOf(0) == '0')
{
string = string.substring(1);
}
One simple solution is to use the Javascript slice() method, and pass 1 as a parameter
let str = "khattak01"
let resStr = str.slice(1)
console.log(resStr)
Result : hattak01
var s = "0test";
if(s.substr(0,1) == "0") {
s = s.substr(1);
}
For all 0s: http://jsfiddle.net/An4MY/
String.prototype.ltrim0 = function() {
return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();
const string = '0My string';
const result = string.substring(1);
console.log(result);
You can use the substring() javascript function.
//---- 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));
try
s.replace(/^0/,'')
console.log("0string =>", "0string".replace(/^0/,'') );
console.log("00string =>", "00string".replace(/^0/,'') );
console.log("string00 =>", "string00".replace(/^0/,'') );
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/
String.prototype.trimStartWhile = function(predicate) {
if (typeof predicate !== "function") {
return this;
}
let len = this.length;
if (len === 0) {
return this;
}
let s = this, i = 0;
while (i < len && predicate(s[i])) {
i++;
}
return s.substr(i)
}
let str = "0000000000ABC",
r = str.trimStartWhile(c => c === '0');
console.log(r);
Another alternative to get the first character after deleting it:
// Example string
let string = 'Example';
// Getting the first character and updtated string
[character, string] = [string[0], string.substr(1)];
console.log(character);
// 'E'
console.log(string);
// 'xample'
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.
var str = "0000one two three0000"; //TEST
str = str.replace(/^\s+|\s+$/g,'0'); //ANSWER
Original implementation for this on JS
string.trim():
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}
Another alternative answer
str.replace(/^0+/, '')
var test = '0test';
test = test.replace(/0(.*)/, '$1');
Related
For Example if input string is "Bcoica",
the length of string between matching characters (between two c's) should return 2
You may try out as,
let mystr = "Bracelet";
function distanceBetweenDuplicateCharacters(char,str){
return str.substr( str.indexOf(char) + 1 ).indexOf(char);
};
console.log(distanceBetweenDuplicateCharacters('e',mystr));
You could use String#indexOf with a starting index.
var string = 'Bcoica',
first = string.indexOf('c'),
second = string.indexOf('c', first + 1);
console.log(second - first - 1);
This is a way you can approach this problem.
Just use indexOf and make a prototype with it for conveniecnce.
var string = "Bcoica";
String.prototype.sizeBetween = function(startChar, endChar) {
//we first get the position of the first char in string
var target = this;
if(startChar===endChar){ // if it's equal we go to the next character
startChar = target.indexOf(startChar);
endChar = target.indexOf(endChar, startChar+1)
} else {
startChar = target.indexOf(startChar);
endChar = target.indexOf(endChar);
}
return endChar-startChar-1; //just return the diference between the two numbers
};
console.log(string.sizeBetween("c","c"));
i have comma separated string like
var test = 1,3,4,5,6,
i want to remove particular character from this string using java script
can anyone suggests me?
JavaScript strings provide you with replace method which takes as a parameter a string of which the first instance is replaced or a RegEx, which if being global, replaces all instances.
Example:
var str = 'aba';
str.replace('a', ''); // results in 'ba'
str.replace(/a/g, ''); // results in 'b'
If you alert str - you will get back the same original string cause strings are immutable.
You will need to assign it back to the string :
str = str.replace('a', '');
Use replace and if you want to remove multiple occurrence of the character use
replace like this
var test = "1,3,4,5,6,";
var newTest = test.replace(/,/g, '-');
here newTest will became "1-3-4-5-6-"
you can make use of JavaScript replace() Method
var str="Visit Microsoft!";
var n=str.replace("Microsoft","My Blog");
var test = '1,3,4,5,6';
//to remove character
document.write(test.replace(/,/g, ''));
//to remove number
function removeNum(string, val){
var arr = string.split(',');
for(var i in arr){
if(arr[i] == val){
arr.splice(i, 1);
i--;
}
}
return arr.join(',');
}
var str = removeNum(test,3);
document.write(str); // output 1,4,5,6
You can also
var test1 = test.split(',');
delete test1[2];
var test2 = test1.toString();
Have fun :)
you can split the string by comma into an array and then remove the particular element [character or number or even string] from that array. once the element(s) removed, you can join the elements in the array into a string again
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
You can use this function
function removeComma(inputNumber,char='') {
return inputNumber.replace(/,/g, char);
}
Update
function removeComma(inputNumber) {
inputNumber = inputNumber.toString();
return Number(inputNumber.replace(/,/g, ''));
}
I have this string:
var str = "? this is a ? test ?";
Now I want to get this:
var newstr = "this is a ? test";
As you see I want to remove just those ? surrounding (in the beginning and end) that string (not in the middle of string). How can do that using JavaScript?
Here is what I have tried:
var str = "? this is a ? test ?";
var result = str.trim("?");
document.write(result);
So, as you see it doesn't work. Actually I'm a PHP developer and trim() works well in PHP. Now I want to know if I can use trim() to do that in JS.
It should be noted I can do that using regex, but to be honest I hate regex for this kind of jobs. Anyway is there any better solution?
Edit: As this mentioned in the comment, I need to remove both ? and whitespaces which are around the string.
Search for character mask and return the rest without.
This proposal the use of the bitwise not ~ operator for checking.
~ is a bitwise not operator. It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:
value ~value boolean
-1 => 0 => false
0 => -1 => true
1 => -2 => true
2 => -3 => true
and so on
function trim(s, mask) {
while (~mask.indexOf(s[0])) {
s = s.slice(1);
}
while (~mask.indexOf(s[s.length - 1])) {
s = s.slice(0, -1);
}
return s;
}
console.log(trim('??? this is a ? test ?', '? '));
console.log(trim('abc this is a ? test abc', 'cba '));
Simply use:
let text = '?? something ? really ??'
text = text.replace(/^([?]*)/g, '')
text = text.replace(/([?]*)$/g, '')
console.log(text)
A possible solution would be to use recursive functions to remove the unwanted leading and trailing characters. This doesn't use regular expressions.
function ltrim(char, str) {
if (str.slice(0, char.length) === char) {
return ltrim(char, str.slice(char.length));
} else {
return str;
}
}
function rtrim(char, str) {
if (str.slice(str.length - char.length) === char) {
return rtrim(char, str.slice(0, 0 - char.length));
} else {
return str;
}
}
Of course this is only one of many possible solutions. The function trim would use both ltrim and rtrim.
The reason that char is the first argument and the string that needs to be cleaned the second, is to make it easier to change this into a functional programming style function, like so (ES 2015):
function ltrim(char) {
(str) => {
<body of function>
}
}
// No need to specify str here
function ltrimSpaces = ltrim(' ');
Here is one way to do it which checks for index-out-of-bounds and makes only a single call to substring:
String.prototype.trimChars = function(chars) {
var l = 0;
var r = this.length-1;
while(chars.indexOf(this[l]) >= 0 && l < r) l++;
while(chars.indexOf(this[r]) >= 0 && r >= l) r--;
return this.substring(l, r+1);
};
Example:
var str = "? this is a ? test ?";
str.trimChars(" ?"); // "this is a ? test"
No regex:
uberTrim = s => s.length >= 2 && (s[0] === s[s.length - 1])?
s.slice(1, -1).trim()
: s;
Step-by-step explanation:
Check if the string is at least 2 characters long and if it is surrounded by a specific character;
If it is, then first slice it to remove the surrounding characters then trim it to remove whitespaces;
If not just return it.
In case you're weirded out by that syntax, it's an Arrow Function and a ternary operator.
The parenthesis are superfluous in the ternary by the way.
Example use:
uberTrim(''); // ''
uberTrim(' Plop! '); //'Plop!'
uberTrim('! ...What is Plop?!'); //'...What is Plop?'
Simple approach using Array.indexOf, Array.lastIndexOf and Array.slice functions:
Update: (note: the author has requested to trim the surrounding chars)
function trimChars(str, char){
var str = str.trim();
var checkCharCount = function(side) {
var inner_str = (side == "left")? str : str.split("").reverse().join(""),
count = 0;
for (var i = 0, len = inner_str.length; i < len; i++) {
if (inner_str[i] !== char) {
break;
}
count++;
}
return (side == "left")? count : (-count - 1);
};
if (typeof char === "string"
&& str.indexOf(char) === 0
&& str.lastIndexOf(char, -1) === 0) {
str = str.slice(checkCharCount("left"), checkCharCount("right")).trim();
}
return str;
}
var str = "???? this is a ? test ??????";
console.log(trimChars(str, "?")); // "this is a ? test"
to keep this question up to date using an ES6 approach:
I liked the bitwise method but when readability is a concern too then here's another approach.
function trimByChar(string, character) {
const first = [...string].findIndex(char => char !== character);
const last = [...string].reverse().findIndex(char => char !== character);
return string.substring(first, string.length - last);
}
Using regex
'? this is a ? test ?'.replace(/^[? ]*(.*?)[? ]*$/g, '$1')
You may hate regex but after finding a solution you will feel cool :)
Javascript's trim method only remove whitespaces, and takes no parameters. For a custom trim, you will have to make your own function. Regex would make a quick solution for it, and you can find an implementation of a custom trim on w3schools in case you don't want the trouble of going through the regex creation process. (you'd just have to adjust it to filter ? instead of whitespace
This in one line of code which returns your desire output:
"? this is a ? test ?".slice(1).slice(0,-1).trim();
I have a number say 2,500.00 and i want to convert the number into 2.500,00. So, we can replace the special character using replace like
var x = 2,500.00;
x.replace(/,/g,".");
and for "Dot" also, we can do it. But in this case, it won't work because when we apply replace function for comma as above, the number will become 2.500.00 and if we apply now, it will become as 2,500,00.
So is there any way to convert 2,500.00 into 2.500,00 ?
String.prototype.replace can take a function:
'2,123,500.00'.replace(/[,.]/g, function(c){ return c===',' ? '.' : ','; });
You can use:
var x = '2,123,500.00';
var arr = x.split('.');
var y = arr[0].replace(/,/g, '.') + ',' + arr[1];
//=> 2.123.500,00
You're in luck, .replace() accept a function as second argument. That function has the matched string as argument and the returned value will be the replace_by value of .replace().
In short, you can simply check what the matched string is and return the right value :
var str = "2,500.00";
var changed_str = str.replace(/,|\./g, function(old){
if (old === '.')
return ',';
else if (old === ',')
return '.';
});
document.write(changed_str)
Why not use the built-in methods to format your numbers correctly?
Number.toLocaleString() would work just fine here.
If you actually have a number as you said, you can easily achieve this using the right locale. If you have a String representation of your number, you would first have to parse it.
This (now) works for any number of commas or dots, even if trailing or leading dots or commas.
HTML:
<div id="result"></div>
JS:
var x = '.,2.123,50.0.00.';
var between_dots = x.split('.');
for (var i = 0; i < between_dots.length; i++) {
between_dots[i] = between_dots[i].replace(/,/g, '.');
}
var y = between_dots.join(',');
document.getElementById('result').innerHTML = y;
Here's the JSFiddle
How can i do to search if a Javascript String contains the following pattern :
"#aRandomString.temp"
I would like to know if the String contains # character and then any String and then ".temp" string.
Thanks
This one liner should do the job using regex#test(Strng):
var s = 'foo bar #aRandomString.temp baz';
found = /#.*?\.temp/i.test(s); // true
Use indexOf to find a string within a string.
var string = "#aRandomString.temp";
var apos = string.indexOf("#");
var dtemp = string.indexOf(".temp", apos); // apos as offset, invalid: ".temp #"
if (apos !== -1 && dtemp !== -1) {
var aRandomString = string.substr(apos + 1, dtemp - apos);
console.log(aRandomString); // "aRandomString"
}
You can try this
var str = "#something.temp";
if (str.match("^#") && str.match(".temp$")) {
}
demo
You can use the match function.
match expects the regular expression.
function myFunction()
{
var str="#someting.temp";
var n=str.test(/#[a-zA-Z]+\.temp/g);
}
Here is a demo: http://jsbin.com/IBACAB/1