I am running through some exercises and run into this on codewars. Its a simple exercise with Instructions to create a function called shortcut to remove all the lowercase vowels in a given string.
Examples:
shortcut("codewars") // --> cdwrs
shortcut("goodbye") // --> gdby
I am newbie so I thought up this solution. but it doesn't work and I have no idea why
function shortcut(string){
// create an array of individual characters
var stage1 = string.split('');
// loop through array and remove the unneeded characters
for (i = string.length-1; i >= 0; i--) {
if (stage1[i] === "a"||
stage1[i] === "e"||
stage1[i] === "i"||
stage1[i] === "o"||
stage1[i] === "u") {
stage1.splice(i,1)
;}
};
// turn the array back into a string
string = stage1.join('');
return shortcut;
}
My gut is telling me that it will probably something to like split and join not creating "true" array's and strings.
I did it at first with a regex to make it a little more reusable but that was a nightmare. I would be happy to take suggestions on other methods of acheiving the same thing.
You are returning the function itself, instead of returning string
Using regex:
var str = 'codewars';
var regex = /[aeiou]/g;
var result = str.replace(regex, '');
document.write(result);
if interested in Regular Expression ;)
function shortcut(str) {
return str.replace(/[aeiou]/g, "");
}
I'm trying to write a Regex that will ignore the first character of a string and start with the second character.
e.g.
str = "14";
test = "4";
This will match ONLY if 4 is is position 2 (end of the string) and NOT at the start, the following will fail
str = "21";
test = "4";
I'm rubbish at Regex and all the options I've tried so far haven't worked.
My current code is like so
filters = filters.replace(/,\s*$/, '');
objRegex = new RegExp('\\/^.{1}(.*)/' + filters, 'gi');
Where filters is a random string consisting of two characters. The current Regex was copied from another SO post but it doesn't work and given my limited knowledge I'm not sure how to make it work, anyone able to help?
Thanks!
I think a Regex is a bit overkill, how about something like this:
var stringToSearch = '14';
var stringToFind = '4';
if (stringToSearch && stringToSearch.length === 2 &&
stringToSearch[1] === stringToFind) {
// do something
}
Just use substring method ?
str = "14";
test = "4";
var str = str.substring(0, 2);
Use following pattern:
"^[\w]{1}4$"
How do I truncate a string after or before a pattern?
Say if I have a string "abcdef" I need to truncate everything after "abc" so the output will be:
def
and if i say truncate before "def" the output should be:
abc
Below is the code that I tried
var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc"), str1.length);
console.log(str2);
I didn't get the output.
I'm stuck here any help will be much appreciated.
You need to pass length of "abc" as the 2nd argument in substr method
var str1 = "abcdefgh";
var pattern = "abc";
var str2 = str1.substr(str1.indexOf(pattern), pattern.length); <-- check this line
console.log(str2);
However above code might return unexpected results for patterns which are not present in the string.
var str1 = "abcdefgh";
var pattern = "bcd";
var str2 = "";
if(str1.indexOf(pattern)>=0) //if a pattern is not present in the source string indexOf method returns -1
{
//to truncate everything before the pattern
//outputs "efgh"
str2 = str1.substr(str1.indexOf(pattern)+pattern.length, str1.length);
console.log("str2: "+str2);
// if you want to truncate everything after the pattern & pattern itself
//outputs "a"
str3 = str1.substr(0, str1.indexOf(pattern));
console.log("str3: "+str3);
}
var str = "sometextabcdefine";
var pattern = "abc";
var truncateBefore = function (str, pattern) {
return str.slice(str.indexOf(pattern) + pattern.length);
};
var truncateAfter = function (str, pattern) {
return str.slice(0, str.indexOf(pattern));
}
console.log(truncateBefore(str, pattern)); // "define"
console.log(truncateAfter(str, pattern)); // "sometext"
Please see the below code:
var str1 = "abcdefgh";
var str2 = str1.substr(str1.indexOf("abc")+3, str1.length);
alert(str2);
You were correct but one thing you missed is doing +3 in the indexOf.
the indexOf("abc") would return 0 which in turn will give you thw whole string again.
Or check out this fiddle link:
Working Fiddle
How about something like this:
function truncateAfter(original, pattern) {
return original.substring(0, original.indexOf(pattern) + pattern.length);
}
What this does is find the first index of the pattern you're looking for, and return a substring of the original string that starts at the beginning and ends after the first instance of the pattern.
Example Usage:
truncateAfter('dabcdefghi', 'abc');
>> 'dabc'
If instead you want to truncate the output before and after the pattern you're looking for, would just checking if the pattern is in the string and then using the pattern as the output be what you're looking for?
function truncate(original, pattern) {
if (original.indexOf(pattern) != -1) {
return pattern;
}
}
Example Usage:
truncate('dabcdefghi', 'abc');
>> 'abc'
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');
So I would like to know what's inside the string for example:
var str = "a"; // Letter
var str = "1"; // Number
var str = "["; // Special
var str = "#"; // Special
var str = "+"; // Special
Is there any pre defined javascript function for this? Otherwise I will make it with regex :)
if (/^[a-zA-Z]$/.test(str)){
// letter
} else if (/^[0-9]$/.test(str)){
// number
} else {
// other
};
Of course this only matches one character so 'AA' would end up in the //other section.
They are all strings...
There isn't anything built in that will do what you want.
A regex may be a good solution, though you have not really provided enough information for one.
if(isNaN(string)){
//yes is a string
}