JavaScript endWith() - javascript

I'm having trouble getting the following to work
if(str.endsWith('+')
{
alert("ends in plus sign")
}
How do I escape the plus sign? I've tried /\ +/ but it doesn't work.

There is no endsWith method in JavaScript, so instead use:
if (str.substr(-1) === "+") {
alert("ends in plus sign")
}

The Javascript String type doesn't have an endsWith function, but you can give it one if you like:
if (!String.prototype.endsWith) {
(function() {
String.prototype.endsWith = String_endsWith;
function String_endsWith(sub) {
return this.length >= sub.length && this.substring(this.length - sub.length) == sub;
}
})();
}
Or if you don't mind unnamed functions:
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(sub) {
return this.length >= sub.length && this.substring(this.length - sub.length) == sub;
};
}
Either way, you could then do:
if ("foo".endsWith("oo")) {
// ...
}

String.prototype.endswith= function(c){
if(!c) return this.charAt(this.length - 1);
else{
if(typeof c== "string") c= RegExp(c + "$");
return c.test(this);
}
}
var s='Tell me more:', s2='Tell me about part 2:';
s.endsWith() // returns ':';
s.endsWIth(':') // returns true, last character is ':';
s2.endsWIth(/\d:?/) // returns true. string ends with a digit and a (possible) colon

Use RegExp:
a = "csadda+"
if (a.match(/.*\+$/)) {
alert("Ends");
}

Related

Valid Parentheses. Gives a wrong boolean (JS problems on LeetCode)

Trying to solve a problem at LeetCode called "Valid Parentheses".
Conditions are:
Given a string s containing just the characters '(', ')', '{', '}',
'[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open
brackets must be closed in the correct order.
I wrote a function and it's working in this snippet:
let arr = ['()']
var isValid = function (data) {
let stack = [];
const bracketsArray = {
'{':'}',
'[':']',
'(':')'
}
for (i=0; i < data[0].length; i++) {
if (data[0][i] == '{' || data[0][i] == '(' || data[0][i] == '[') {
stack.push(data[0][i]);
} else if (data[0][i] == '}' || data[0][i] == ']' || data[0][i] == ')') {
if (bracketsArray[stack[stack.length-1]] == data[0][i]) {
stack.pop()
}
}
}
if (stack.length == 0) {
return true
} else {
return false
}
}
console.log(isValid(arr))
Function gives a correct output (boolean)
But when I run this code at LeetCode for some reason the same code gives me a wrong boolean.
Don't understand what is wrong.
/**
* #param {string} s
* #return {boolean}
*/
var isValid = function(s) {
let stack = [];
const bracketsArray = {
'{':'}',
'[':']',
'(':')'
}
for (i=0; i < s[0].length; i++) {
if (s[0][i] == '{' || s[0][i] == '(' || s[0][i] == '[') {
stack.push(s[0][i]);
} else if (s[0][i] == '}' || s[0][i] == ']' || s[0][i] == ')') {
if (bracketsArray[stack[stack.length-1]] == s[0][i]) {
stack.pop()
}
}
}
if (stack.length == 0) {
return true;
} else {
return false;
}
};
Any advice?
On LeetCode the function parameter is a string, but in your tests you are passing an array, and also your function code expects an array, since it accesses the string with s[0], instead of s.
Unrelated, but:
Your code fails when the input is just a closing bracket. This is because your loop doesn't break with return false when a non-matching closing bracket is encountered. This should happen in the else part of if (bracketsArray[stack[stack.length-1]] == s[i]) {
Don't use an undeclared variable i, which will then implicitly become a global variable (if running in non-strict mode).
Don't name your variable bracketsArray since it is not an array.
Make more use of that object, instead of making three comparisons with opening brackets.
The final if...then is overkill for just returning the value of a boolean expression.
So:
var isValid = function(s) {
const stack = [];
const brackets = {
'{':'}',
'[':']',
'(':')'
}
const closing = Object.values(brackets);
for (let ch of s) {
if (brackets[ch]) {
stack.push(brackets[ch]);
} else if (ch == stack.at(-1)) {
stack.pop()
} else if (closing.includes(ch)) {
return false;
}
}
return !stack.length;
};
console.log(isValid("{([])}")); // true
console.log(isValid("]")); // false
The way you are accessing the current character of the iteration is wrong. Instead of doing s[0][i], simply do s[i].
s[0][i] accesses the first character, and then attempts to get the i-th entry from it (which is undefined).
var isValid = function(s) {
let stack = [];
const bracketsArray = {
'{':'}',
'[':']',
'(':')'
}
for (i=0; i < s.length; i++) {
if (s[i] == '{' || s[i] == '(' || s[i] == '[') {
stack.push(s[i]);
} else if (s[i] == '}' || s[i] == ']' || s[i] == ')') {
if (bracketsArray[stack[stack.length-1]] == s[i]) {
stack.pop()
}
}
}
if (stack.length == 0) {
return true;
} else {
return false;
}
};
isValid("{([])}") // true
isValid("{([)}") // false

Recursively add to strings in JS

I'm tackling a recursion problem that returns a string of "hi"'s where the first "hi" has a capital H and the string ends with an exclamation point. I have the code below so far but I'm not sure how to prevent subsequent occurrences of "hi" having a capital H. Any guidance would be welcome.
function greeting(n) {
if (n === 0) {
return "";
} else if (n === 1) {
return "Hi!"
} else {
return `${'Hi' + greeting(n - 1)}`
}
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!
One way to work around your problem is to pass a flag to the function which indicates whether this is the first call, and only in that case capitalise the hi. Note that you can simplify the code slightly by returning a ! when n == 0; then you don't need to special case n == 1:
function greeting (n, first = true) {
if (n === 0) {
return "!";
}
else {
return `${(first ? 'Hi' : 'hi') + greeting(n - 1, false)}`
}
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!
Just a .toLowerCase() is missing in your code.
`${'Hi' + greeting(n - 1).toLowerCase()}`
You don't need the n === 1 step.
function greeting(n) {
if (n === 0) {
return "!";
} else {
return `${'Hi' + greeting(n - 1).toLowerCase()}`
//------------------------------^^^^^^^^^^^^^^
}
}
console.log(greeting(3)) // should return Hihihi!
console.log(greeting(5)) // should return Hihihihihi!

How to convert a string with arrays to an array [duplicate]

This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Closed 4 years ago.
How do I convert this piece of response into a valid array?
I want to perform an Object.map on the data:
var user_roles = "['store_owner', 'super_admin']";
This is not a valid JSON so I can't use JSON.parse
Right, most answers posted here suggest using JSON.parse and then get downvoted 3 times before getting deleted. What people overlook here is the lack of JSON-compliant quotation. The string IS, however, valid JavaScript. You can do the following:
const obj = {
thing: "['store_owner', 'super_admin']",
otherThing: "['apple', 'cookies']"
}
for (const key in obj) {
const value = obj[key];
obj[key] = eval(value);
}
console.log(obj);
Output will be a valid javascript object:
{"thing":["store_owner","super_admin"],"otherThing":["apple","cookies"]}
Be careful with eval(), though! javascript eval() and security
You can try it here: https://es6console.com/jjqvrnhg/
I took the polyfill for JSON.parse I found here
And replaced the meaning of a string to consist of '' single quote notation:
/*
json_parse.js
2016-05-02
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
This file creates a json_parse function.
json_parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = json_parse(text, function (key, value) {
var a;
if (typeof value === "string") {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
*/
/*jslint for */
/*property
at, b, call, charAt, f, fromCharCode, hasOwnProperty, message, n, name,
prototype, push, r, t, text
*/
var json_parse = (function () {
"use strict";
// This is a function that can parse a JSON text, producing a JavaScript
// data structure. It is a simple, recursive descent parser. It does not use
// eval or regular expressions, so it can be used as a model for implementing
// a JSON parser in other languages.
// We are defining the function inside of another function to avoid creating
// global variables.
var at; // The index of the current character
var ch; // The current character
var escapee = {
"\"": "\"",
"\\": "\\",
"/": "/",
b: "\b",
f: "\f",
n: "\n",
r: "\r",
t: "\t"
};
var text;
var error = function (m) {
// Call error when something is wrong.
throw {
name: "SyntaxError",
message: m,
at: at,
text: text
};
};
var next = function (c) {
// If a c parameter is provided, verify that it matches the current character.
if (c && c !== ch) {
error("Expected '" + c + "' instead of '" + ch + "'");
}
// Get the next character. When there are no more characters,
// return the empty string.
ch = text.charAt(at);
at += 1;
return ch;
};
var number = function () {
// Parse a number value.
var value;
var string = "";
if (ch === "-") {
string = "-";
next("-");
}
while (ch >= "0" && ch <= "9") {
string += ch;
next();
}
if (ch === ".") {
string += ".";
while (next() && ch >= "0" && ch <= "9") {
string += ch;
}
}
if (ch === "e" || ch === "E") {
string += ch;
next();
if (ch === "-" || ch === "+") {
string += ch;
next();
}
while (ch >= "0" && ch <= "9") {
string += ch;
next();
}
}
value = +string;
if (!isFinite(value)) {
error("Bad number");
} else {
return value;
}
};
var string = function () {
// Parse a string value.
var hex;
var i;
var value = "";
var uffff;
// When parsing for string values, we must look for " and \ characters.
if (ch === "\'") {
while (next()) {
if (ch === "\'") {
next();
return value;
}
if (ch === "\\") {
next();
if (ch === "u") {
uffff = 0;
for (i = 0; i < 4; i += 1) {
hex = parseInt(next(), 16);
if (!isFinite(hex)) {
break;
}
uffff = uffff * 16 + hex;
}
value += String.fromCharCode(uffff);
} else if (typeof escapee[ch] === "string") {
value += escapee[ch];
} else {
break;
}
} else {
value += ch;
}
}
}
error("Bad string");
};
var white = function () {
// Skip whitespace.
while (ch && ch <= " ") {
next();
}
};
var word = function () {
// true, false, or null.
switch (ch) {
case "t":
next("t");
next("r");
next("u");
next("e");
return true;
case "f":
next("f");
next("a");
next("l");
next("s");
next("e");
return false;
case "n":
next("n");
next("u");
next("l");
next("l");
return null;
}
error("Unexpected '" + ch + "'");
};
var value; // Place holder for the value function.
var array = function () {
// Parse an array value.
var arr = [];
if (ch === "[") {
next("[");
white();
if (ch === "]") {
next("]");
return arr; // empty array
}
while (ch) {
arr.push(value());
white();
if (ch === "]") {
next("]");
return arr;
}
next(",");
white();
}
}
error("Bad array");
};
var object = function () {
// Parse an object value.
var key;
var obj = {};
if (ch === "{") {
next("{");
white();
if (ch === "}") {
next("}");
return obj; // empty object
}
while (ch) {
key = string();
white();
next(":");
if (Object.hasOwnProperty.call(obj, key)) {
error("Duplicate key '" + key + "'");
}
obj[key] = value();
white();
if (ch === "}") {
next("}");
return obj;
}
next(",");
white();
}
}
error("Bad object");
};
value = function () {
// Parse a JSON value. It could be an object, an array, a string, a number,
// or a word.
white();
switch (ch) {
case "{":
return object();
case "[":
return array();
case "\'":
return string();
case "-":
return number();
default:
return (ch >= "0" && ch <= "9")
? number()
: word();
}
};
// Return the json_parse function. It will have access to all of the above
// functions and variables.
return function (source, reviver) {
var result;
text = source;
at = 0;
ch = " ";
result = value();
white();
if (ch) {
error("Syntax error");
}
// If there is a reviver function, we recursively walk the new structure,
// passing each name/value pair to the reviver function for possible
// transformation, starting with a temporary root object that holds the result
// in an empty key. If there is not a reviver function, we simply return the
// result.
return (typeof reviver === "function")
? (function walk(holder, key) {
var k;
var v;
var val = holder[key];
if (val && typeof val === "object") {
for (k in val) {
if (Object.prototype.hasOwnProperty.call(val, k)) {
v = walk(val, k);
if (v !== undefined) {
val[k] = v;
} else {
delete val[k];
}
}
}
}
return reviver.call(holder, key, val);
}({"": result}, ""))
: result;
};
}());
console.log(json_parse("['store_owner', 'super_admin']"));
Make it JSON compliant
JSON.parse(user_roles.replace(/(?<!\\)'/g,'"')
This works by fixing the reason why your code can't be parsed by JSON. That reason is that JSON doesn't let you use single quotes (') so we change them to Double Quotes (")
EDIT:
I made it so that when a ' is preceded by a \ it will not be replaced with a ".

Recursive palindrome check with JavaScript

I am trying to find out whether a string is a palindrome by recursion using javascript. But I can't figure out what I am missing in the code.
var firstCharacter = function(str) {
return str.slice(0, 1);
};
var lastCharacter = function(str) {
return str.slice(-1);
};
var middleCharacters = function(str) {
return str.slice(1, -1);
};
var isPalindrome = function(str) {
if(str.length < 2) {
return true;
} else {
if(firstCharacter(str) == lastCharacter(str)) {
isPalindrome(middleCharacters(str));
} else return false;
}
};
var checkPalindrome = function(str) {
console.log("Is this word a palindrome? " + str);
console.log(isPalindrome(str));
};
checkPalindrome("a");
//Program.assertEqual(isPalindrome("a"), true);
checkPalindrome("matom");
//Program.assertEqual(isPalindrome("motor"), false);
checkPalindrome("rotor");
//Program.assertEqual(isPalindrome("rotor"), true);
For sure something is wrong with the recursive call. I would love to have your help. Thanks. I am attaching the output of my code.
Here is another recursive palindrome.
function checkPalindrome(str){
if(str.length === 1) return true;
if(str.length === 2) return str[0] === str[1];
if(str[0] === str.slice(-1)) return checkPalindrome(str.slice(1,-1))
return false;
}
console.log(checkPalindrome('a')) // true
console.log(checkPalindrome('matom')) // false
console.log(checkPalindrome('rotor')) // true
You defined isPalindrome() to return a value, so if you call it yourself, recursively or otherwise, you need to deal with that return value. Also, your if ... else logic is too complicated, simplify:
var isPalindrome = function(str) {
if (str.length < 2) {
return true;
}
if (firstCharacter(str) == lastCharacter(str)) {
return isPalindrome(middleCharacters(str));
}
return false;
};
const isPalindrome = str => {
const strLen = str.length;
if (strLen < 2) return true;
if (str[0] === str[strLen - 1]) {
return isPalindrome( str.slice(1, strLen - 1) );
}
return false;
};
console.log(isPalindrome('madam'));
Using slice creates an array - if you want to compare the first and last char, you will need to extract the value from the array before applying == -
var firstCharacter = function(str) {
return str.slice(0, 1)[0] // <-- get the first element of the slice
}
var lastCharacter = function(str) {
return str.slice(-1)[0] // <-- get the first element of the slice
}
Here's another recursive solution that uses parameters l (left) and r (right) to check the string using indexes (rather than creating intermediate values with slice) -
const palindrome = (s = "", l = 0, r = s.length - 1) =>
r - l < 2
? true
: s[l] === s[r] && palindrome (s, l + 1, r - 1)
console.log
( palindrome ("motor") // false
, palindrome ("rotor") // true
, palindrome ("racecar") // true
, palindrome ("wow") // true
, palindrome ("i") // true
)
And here's a mutually recursive definition. It's wasteful but it has an elegant form nonetheless -
const pal = ([ s, ...more ]) =>
more.length === 0 || pal2 (more.reverse(), s)
const pal2 = ([ s, ...more ], q) =>
s === q && pal (more.reverse())
console.log
( pal ("motor") // false
, pal ("rotor") // true
, pal ("racecar") // true
, pal ("wow") // true
, pal ("i") // true
)
Here is another way to recursively check for a palindrome in JS:
function isPalindrome(str){
if (str[0] === str[str.length - 1] && str.length > 1) {
isPalindrome(str.substring(1, str.length -1))
return true
}else{
return false
}
}
Here's a simple answer for ya. Basically we are comparing the first character to last character and acting accordingly.
const isPalindrome = str => {
if (str.length <= 1) return true;
if (str[0] !== str[str.length - 1]) return false;
return isPalindrome(str.slice(1,-1))
}
const isPalindrome = str => {
// base case
if(str.length === 1) return true;
if(str.length === 2) return str[0] === str[1];
if(str[0] === str[str.length - 1]) {
return isPalindrome(str.slice(1, -1))
}
return false;
}
you can use recursion
base case
we have a base case (the simple case) if the string is one char we simply returns true.
if it has two chars we check if the first char is identical to the second and we return true if they are.
recursive case
if it is more than two chars we check if the first and last chars are identical or not if they are not we simply return false
but if they are identical so we now want to do the same thing with other chars so we call the same function with the same string but removing the first and last chars because we already know that they are identical and we keep going until we reach the base case.
hope this be useful
some tests
isPalindrome('p') // true
isPalindrome('po') // false
isPalindrome('pp') // true
isPalindrome('pop') //true
What's about this solution ?
function isPalindrome(str){
if (str.length > 3) return isPalindrome(str.substring(1, str.length-1));
return str[0] === str[str.length-1];
}
My simple implementation for a recursive palindrome check, in 2022:
function isPalindrome(str) {
if (!str.length || str.length === 1) return true;
return str[0] === str.at(-1) ? isPalindrome(str.substr(1, str.length - 2)) : false;
}
console.log(isPalindrome('catotac'));
Iterations breakdown:
// 1st iteration:
isPalindrome('catotac');
//2nd iteration
isPalindrome('atota');
//3rd
isPalindrome('tot');
// 4th iteration
isPalindrome('o'); // true

Check, if word has a same end and start in JavaScript

I'm searching for how can I check if word has a same end and start. There is my code:
JavaScript:
function Check() {
var value = document.getElementById("input").value;
if (value == startsWith(endsWith()) && value == endsWith(startsWith())) {
return alert("Yes");
} else {
return alert("No");
}
}
<input id="input" style="margin:20px;" type="text"><br>
<button id="button" onclick="Check();">Check</button>
<p id="demo" style="color:white;">Answer</p>
Just check the first and last character of the string:
if(value[0] == value[value.length-1])
{
alert('Yes');
}
else
{
alert('No');
}
Try below function.
I am comparing first character and last character of your input string.
function Check() {
var value = document.getElementById("input").value;
if (value.charAt(0) === value.charAt(value.length - 1)) {
return alert("Yes");
} else {
return alert("No");
}
}
Use str.length - 1 to get the index of the last character of the string.
function check(str) {
if (str[0] === str[str.length - 1]) {
alert('yes')
} else {
alert('no');
}
}
check('test');
check('tests');
To check first/last n characters you can do this.
function checkMore(str, amount) {
if (str[0] !== str[str.length - 1]) {
alert('no');
return;
} else if (amount !== 1) {
return checkMore(str.slice(1, str.length - 1), amount - 1);
}
alert('yes');
}
checkMore('stests', 1);
checkMore('stests', 2);
checkMore('stests', 3);
And to check the whole string (basically checking if the string is palindrome).
function checkPalindrome(str) {
if (str.length === 0 || str.length === 1) {
alert('yes');
return;
}
if (str[0] !== str[str.length - 1]) {
alert('no');
return;
}
checkPalindrome(str.slice(1, str.length - 1));
}
checkPalindrome('car');
checkPalindrome('carac');
checkPalindrome('carrac');
You can use match() or indexOf(). Both work, but both search the whole string. It is more efficient to extract the substring in the relevant place and compare it with the one you expect there:
function Check ( word ) {
return word.charAt(0) == word.charAt( word.length - 1 )
}
<button tye="button" onclick="alert( Check('Hello') )">Check 'Hello'</button>
<button tye="button" onclick="alert( Check('HelloH') )">Check 'HelloH'</button>
Of course, you might as well use a regular expression, with a smart regex engine it should be efficient as well (and your code is more concise):
function Check ( word ) {
return /^(.).*\1$|^.$/.test( word )
}
<button tye="button" onclick="alert( Check('Hello') )">Check 'Hello'</button>
<button tye="button" onclick="alert( Check('WoW') )">Check 'WoW'</button>
var value = "wow"
return (value[0] === value[value.length - 1] ? true : false)
0th index will contain starting character and value.length - 1 will contain ending character. If they are equal it will return true and false otherwise.
You can use .split('' ) to split a string by spaces, so into words. It splits it into an array, so you can compare index [0] to index [length-1]
For example
function Check(string) {
let arr = string.split(' ');
return arr[0] == arr[arr.length-1];
}
Use regex:
if (/^(.).*\1$|^.$/.test(value))
// first and last are same letter

Categories

Resources