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)
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
str.replace(/^\|/, "");
This will remove the first character if it's a |.
var newstring = oldstring.substring(1);
If you're not sure what the first character will be ( 0 or | ) then the following makes sense:
// 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 '|' 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' ).
Try this:
var str = "|0|0|0|0";
str.replace(str.charAt(0), "");
Avoid using substr() as it's considered deprecated.
It literally is what you suggested.
"|0|0|0".replace('|', '')
returns "0|0|0"
"|0|0|0|0".split("").reverse().join("") //can also reverse the string => 0|0|0|0|
Related
I want to remove the % character from my string if the % character present in the string, then it should check whether it is in the beginning or end then it should trim the value then the provide the result.
Eg: var str = "Value%" or "%Value" or "%Value%"
The result should be = Value.
Eg: var str="Va%ue"
The result should be =Va%ue.
Eg: var str= "Value"
The result should be = Value.
Thanks in Advance
str = (str[0] == '%' || str.endsWith('%')? str.replace(/%/g, '') : str);
Check if the string starts or ends with % before replacing
Your regex basically needs to have two alternatives combined with an 'or' sign.
You use ^ to signal beginning and $ to signal ending, then combine them with |.
The regex for percent lookup: ^%|%$.
If you put that in to the replace() function and add the global lookup flag g, you can easily achieve what you're looking for:
const percentLookupRegex = /^%|%$/g;
str.replace(percentLookupRegex, '');
Here's a live example:
https://regex101.com/r/nAK64n/2
If you want to use regex then you should look into the anchors ^ and $
Eg.
str.replace(/^%/, '');
Will replace % in the beginning of the line with nothing.
An alternative approach is to use startsWith and endsWith and then slice the string appropriately:
if (str.startsWith('%') {
str = str.slice(1);
}
Removing a % at the end of the string is left as an exercise for the reader
str = (str.indexOf('%') === 0) ? str.substring(1) : str; // check for first character
str = (str.lastIndexOf('%') === (str.length - 1)) ? str.substring(0, str.length - 1) : str; //check for last character
This will only check for first and last character and remove only those
I have a string - "hi#i#am#hum'#'an ";
I want to split the string for an operator #, but don't want to split the string which is under single quote.
So I want the result - ["hi","i","am","hum#an"]
Try
input.split( /#(?!')/ )
Demo
var output = "hi#i#am#hum'#'an ".split( /#(?!')/ ).map( s => s.replace(/'#'/g, "#") );
console.log( output );
Here is another solution, not a one liner though. First replace '#' with some temporary character. Then apply the split, and replace temp character with #.
var str = "hi#i#am#hum'#'an";
str = str.replace(/'#'/g, '&');
str = str.split('#');
str = str.map(s => s.replace(/&/g, '#'))
console.log(str);
I am having the following string,
var str = "/\S\w\djoseph/";
I just wanted to fetch the characters that are not in the following pattern,
/\\(\w|\d)/
I mean I just want to extract joseph from the above string. I have tried with the following but my regex is not working as expected.
var str = "/\S\w\djoseph/";
var mat = /[^\\(\w|\d)]/g.exec(str);
console.log(mat); //["/"]
Can anyone help me to get the required string from the target string of mine?
You can use this regex in .replace with a callback:
/\S\whello\s\d/.source.replace(/(\\[wsd])|(.)/g, function($0, $1, $2){
return ($1 == undefined ? "" : $1) + ($2 != undefined ? $2.toUpperCase() : "");
})
//=> "\S\wHELLO\s\d"
This will uppercase anything that is not \w or \s or \d.
How about replacing everything that matches \. with the empty string?
var a = '\\a\\btest\\c\\d';
var result = a.replace(/\\./g, '');
console.log(result);
Using JavaScript, how can I remove the last comma, but only if the comma is the last character or if there is only white space after the comma? This is my code.
I got a working fiddle. But it has a bug.
var str = 'This, is a test.';
alert( removeLastComma(str) ); // should remain unchanged
var str = 'This, is a test,';
alert( removeLastComma(str) ); // should remove the last comma
var str = 'This is a test, ';
alert( removeLastComma(str) ); // should remove the last comma
function removeLastComma(strng){
var n=strng.lastIndexOf(",");
var a=strng.substring(0,n)
return a;
}
This will remove the last comma and any whitespace after it:
str = str.replace(/,\s*$/, "");
It uses a regular expression:
The / mark the beginning and end of the regular expression
The , matches the comma
The \s means whitespace characters (space, tab, etc) and the * means 0 or more
The $ at the end signifies the end of the string
you can remove last comma from a string by using slice() method, find the below example:
var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
strVal = strVal.slice(0, -1);
}
Here is an Example
function myFunction() {
var strVal = $.trim($('.txtValue').text());
var lastChar = strVal.slice(-1);
if (lastChar == ',') { // check last character is string
strVal = strVal.slice(0, -1); // trim last character
$("#demo").text(strVal);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="txtValue">Striing with Commma,</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
function removeLastComma(str) {
return str.replace(/,(\s+)?$/, '');
}
In case its useful or a better way:
str = str.replace(/(\s*,?\s*)*$/, "");
It will replace all following combination end of the string:
1. ,<no space>
2. ,<spaces>
3. , , , , ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>
The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:
let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '
https://jsfiddle.net/dc8moa3k/
long shot here
var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true) {
currentIndex=pattern.lastIndex;
}
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
alert(sentence);
Remove last comma. Working example
function truncateText() {
var str= document.getElementById('input').value;
str = str.replace(/,\s*$/, "");
console.log(str);
}
<input id="input" value="address line one,"/>
<button onclick="truncateText()">Truncate</button>
First, one should check if the last character is a comma.
If it exists, remove it.
if (str.indexOf(',', this.length - ','.length) !== -1) {
str = str.substring(0, str.length - 1);
}
NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)
you can remove last comma:
var sentence = "I got,. commas, here,";
sentence = sentence.replace(/(.+),$/, '$1');
console.log(sentence);
To remove the last comma from a string, you need
text.replace(/,(?=[^,]*$)/, '')
text.replace(/,(?![^,]*,)/, '')
See the regex demo. Details:
,(?=[^,]*$) - a comma that is immediately followed with any zero or more chars other than a comma till end of string.
,(?![^,]*,) - a comma that is not immediately followed with any zero or more chars other than a comma and then another comma.
See the JavaScript demo:
const text = '1,This is a test, and this is another, ...';
console.log(text.replace(/,(?=[^,]*$)/, ''));
console.log(text.replace(/,(?![^,]*,)/, ''));
Remove whitespace and comma at the end use this,
var str = "Hello TecAdmin, ";
str = str.trim().replace(/,(?![^,]*,)/, '')
// Output
"Hello TecAdmin"
The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.
EDIT: Is it really that confusing?
'This, is a random string'
Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.
With or without Regex.
I suggest two processes and also consider removing space as well. Today I got this problem and I fixed this by writing the below code.
I hope this code will help others.
//With the help of Regex
var str = " I am in Pakistan, I am in India, I am in Japan, ";
var newstr = str.replace(/[, ]+$/, "").trim();
console.log(newstr);
//Without Regex
function removeSpaceAndLastComa(str) {
var newstr = str.trim();
var tabId = newstr.split(",");
strAry = [];
tabId.forEach(function(i, e) {
if (i != "") {
strAry.push(i);
}
})
console.log(strAry.join(","));
}
removeSpaceAndLastComa(str);
If you are targeting es6, then you can simply do this
str = Array.from( str ).splice(0, str.length - 1).join('');
This Array.from(str) converts the string to an array (so we can slice it)
This splice( 0 , str.length - 1 ) returns an array with the items from the array sequentially except the last item in the array
This join('') joins the entries in the array to form a string
Then if you want to make sure that a comma actually ends the string before performing the operation, you can do something like this
str = str.endsWith(',') ? Array.from(str).splice(0,str.length - 1).join('') : str;
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');