I want to check the string starts with '.' eg .net and replace it as net using ternary operator in javascript.I want to replace the below code with ternary operator
arr = ".net"
var val = arr.startsWith('.');
if(val == true)
{
arr = arr.replace('.','');
}
else
{
arr;
}
tried as
arr = arr.startsWith('.') ? arr.replace('.','') : arr;
var arr = '.net'
arr = arr.startsWith('.')
? arr.slice(1)
: arr
You probably don't want to replace the . as there could be a . elsewhere in the string. .slice will just remove the first character and return the rest.
You can use regex for that.
Idea:
Create a pattern which checks for string that starts with .
Use it to replace to blank string.
If a string does not start with ., it will not replace.
function replace(str) {
return str.replace(/^\./, '')
}
console.log(replace('.net'))
console.log(replace('asp.net'))
function removeDot(arr) {
return arr.startsWith('.') ? arr.slice(1) : arr;
}
You can add a function like removeDot, invoke it with whatever string you want and get the output without dot.
Related
for self development purposes I want to create a function with two parameters - string and an array. It should return a string without the letters given in the array.
function filterLetters(str, lettersToRemove) {
}
const str = filterLetters('Achievement unlocked', ['a', 'e']);
Could someone give me any pointers on how to achieve this?
For each letter to be replaced, remove it (i.e. replace it with ''). When done, return the updated string:
function filterLetters(str, lettersToRemove) {
lettersToRemove.forEach(function(letter){
str = str.replaceAll(letter, '');
})
return str
}
Also see How to replace all occurrences of a string in JavaScript.
You can use regex with replaceAll to remove all char from the string.
If you want to consider upper case also then use 'gi' else no need for regex also. str.replaceAll(char, '')
const removeChar = (str, c) => str.replaceAll(new RegExp(`[${c}]`, "gi"), "");
const run = () => {
const str = "Achievement unlocked";
const chars = ["a", "e"];
let result = str;
chars.forEach((char) => {
result = removeChar(result, char);
});
return result;
};
console.log(run());
One easy way to do this would be to just loop over each value in the array and call the replace string method on str with each indices character. The code below does this.
function filterLetters(str, lettersToRemove){
for (const letter of lettersToRemove){
str = str.replaceAll(letter,"");
}
return str;
}
You should just transform the string into array by using split function and loop over that array and check if each character exist in the second argument of your function. To make this function not case sensitive I use toLowerCase to convert character to
function filterLetters(str, lettersToRemove) {
return str.split('').reduce((acc, current)=> {
if(lettersToRemove.indexOf(current.toLowerCase()) == -1){
acc.push(current);
}
return acc;
}, []).join('');
}
const str = filterLetters('Achievement unlocked', ['a', 'e']);
console.log(str);
Create a regular expression by joining the array elements with a | (so a|e), and then use replaceAll to match those letters and replace them with an empty string.
If you want both upper- and lower-case letters removed add the "case-insenstive" flag to the regex. 'gi' rather than 'g'.
function filterLetters(str, lettersToRemove) {
const re = new RegExp(lettersToRemove.join('|'), 'g');
return str.replaceAll(re, '');
}
const str = filterLetters('Achievement unlocked', ['a', 'e']);
console.log(str);
How can the existing code be modified below such that if a string doesn't have a comma in it, it will just output the regular value.
function test() {
//alert(get_ref_docs('12345678,987654321,14439696',1))
alert(get_ref_docs('12345678',1)) -error received here.
alert(get_ref_docs('12345678',1)) -> would like the value alerted "12345678"
}
function get_ref_docs(str,num) {
/*Now strings will be a three element array where
strings[0] contains the full string
strings[1] contains the string before the first comma
strings[2] contains everything after the first comma
*/
var x = str.match(/([^,]*),(.*)/);
return x[num]
}
I think you could use this regex add this to your code:
var x = str.match(/[^,]+/g);
return x && x[num] ? x[num] : str;
If your string contains a comma, and your num is a valid index you will get your value.
If not, the original string will be returned.
For example:
function test() {
console.log(get_ref_docs('12345678,987654321,14439696', 2));
console.log(get_ref_docs('12345678', 1));
console.log(get_ref_docs('12345678,987654321,14439696', 3));
}
function get_ref_docs(str, num) {
var x = str.match(/[^,]+/g);
return x && x[num] ? x[num] : str;
}
test();
No need for a regex here. Just split on coma, like follows:
function get_ref_docs(str, num) {
return str.split(",")[num - 1];
}
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 am trying to write a palindrome code, so I am using the split and reverse methods. Is my below logic correct? Can I directly use the reverse method instead of giving split and then reverse?
If I give == it prints palindrome where as if I give === it prints not palindrome. I am a beginner in JS and I am trying to learn.
var actualWord = "madam"
var splittedWord = actualWord.split();
console.log("splittedWord---->" + splittedWord);
var reversedWord = splittedWord.reverse();
console.log("reversedWord---->" + reversedWord);
console.log("boolean" + reversedWord === actualWord);
if (reversedWord === actualWord) {
console.log("palindrome");
} else {
console.log("not palindrome")
}
Your logic is flawed as split() with no parameter to split by returns the original word, which then means that reverse() has no effect as you're working on a single element array. You are also attempting to check arrays for equality, which will not work.
To do what you require you need to split by '' to generate a character array which you can then reverse() and join() back together to invert the characters of the word. Then you can compare the words to discover if the original was a palindrome. Try this:
var actualWord = "madam"
var reverseWord = actualWord.split('').reverse().join('');
console.log(actualWord, reverseWord);
if (actualWord === reverseWord) {
console.log(actualWord + " IS a palindrome");
} else {
console.log(actualWord + " IS NOT a palindrome")
}
Working example
Taking this a step further you could extract the logic to it's own function and make the string comparison case-insensitive:
console.log('madam', isPalindrome('madam'));
console.log('madame', isPalindrome('madame'));
console.log('raceCAR', isPalindrome('raceCAR'));
function isPalindrome(word) {
var reverseWord = word.split('').reverse().join('');
return word.toLowerCase() === reverseWord.toLowerCase();
}
Example fiddle
Several things needed to make your code correct:
Split the words using .split("") not .split()
Create strings from the arrays using .join("")
Put parentheses around the comparator in your "boolean" line, otherwise the "+" will be performed before the "==="
var actualWord = "madam";
var splittedWord = actualWord.split("");
log("splittedWord---->" + splittedWord.join(""));
var reversedWord = splittedWord.reverse();
log("reversedWord---->" + reversedWord.join(""));
log("boolean---->" + (reversedWord.join("") === actualWord));
if (reversedWord.join("") === actualWord) {
log("palindrome");
} else {
log("not palindrome")
}
function log(str) {
document.body.appendChild(document.createElement("p")).innerHTML = str;
}
The == operator will compare for equality after doing any necessary
type conversions. The === operator will not do the conversion, so if
two values are not the same type === will simply return false. It's
this case where === will be faster, and may return a different result
than ==. In all other cases performance will be the same.
e.g.-
"1" == 1
true
"1" === 1
false
in your case, reversedWord is an array but actualWord is string, hence you get false when using ===, but when you use == JS does the necessary type conversion for you and you get true.
You have to call the split function before the reverse function because you are referring to a string and not an array.
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');