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];
}
Related
I am trying to do a regex match at a specific position in Typescript.
Here's what I have tried.
var str = "0123ABC789"
function matchesAt(rgx: RegExp, s : string, i : number) : string | void {
rgx.lastIndex = i
console.log(rgx.exec(s));
}
matchesAt(/(ABC)/g, str, 4 )
In essence, I am trying to recreate the String.startsWith(string, number) method, but with a regex inside - instead of another string.
I am expecting that the function should only match when the index is 4. any other number should return a nil.
You can use the sticky flag y:
The y flag indicates that the regex attempts to match the target string only from the index indicated by the lastIndex property (and unlike a global regex, does not attempt to match from any later indexes).
function matchesAt(rgx, s, i) {
rgx.lastIndex = i;
return rgx.test(s); // use .test to get boolean result
}
var str = "0123ABC789";
console.log(matchesAt(/ABC/gy, str, 4)); // true
console.log(matchesAt(/ABC/gy, str, 3)); // false!
You can check if matched string length plus i is equal as following lastIndex:
function matchesAt(rgx: RegExp, s : string, i : number) : string | void {
rgx.lastIndex = i
let isMatching = rgx.exec(s);
if (isMatching && isMatching?.length > 1 && rgx.lastIndex - isMatching[1]?.length == i)
return s;
return void null;
}
JavaScript
This is the function which will give the output "true"if there is a repeated character in a string,,
otherwise it will give output "false"
function repeatChar(str) {
for (let char of str.toLowerCase()) {
if (str.indexOf(char) !== str.lastIndexOf(char)) {
return true;
}
}
return false;
}
console.log(repeatChar('aA')); //expected output "true" but here output is "false"... Why??
You're searching for the lowercased character in the original string, which hasn't been converted to all lowercase.
You should replace str with its lowercase version before the loop.
function repeatChar(str) {
str = str.toLowerCase();
for (let char of str) {
if (str.indexOf(char) !== str.lastIndexOf(char)) {
return true;
}
}
return false;
}
console.log(repeatChar('aA')); //expected output "true" but here output is "false"... Why??
Because str.toLowerCase() is ‘aa’ but you’re comparing occurrences in the original string ‘aA’:
// str is still ‘aA’
// str.toLowerCase() returns a *new string* and leaves str unchanged
str.indexOf(char) // “aA”.indexOf(‘a’) === 0
str.lastIndexOf(char) // “aA”.indexOf(‘a’) === 0
When you reference "str.indexOf(char)" in the "if" check you are not referencing the lower case version of str, but rather the original version with upper case.
If you want to reference the lower case version, you can do the following:
function repeatChar(str) {
for (let char of lower_str=str.toLowerCase()) {
if (lower_str.indexOf(char) !== lower_str.lastIndexOf(char)) {
return true;
}
}
return false;
}
console.log(repeatChar('aA'));
str='aA';
str.toLowerCase() is 'aa';
However, unless str is updated i.e. str=str.toLowerCase(), all references to str shall be to its original form i.e. 'aA'.
And, as you rightly know (given you are indeed attempting to use uniform case during comparison), the indexOf() and lastIndexOf() methods are case sensitive
A simpler way to do this would be to construct a Set from the string's characters and compare its size with the original string's length. If they are equal, then there were no repeated characters, as Sets contain only unique values.
function repeatChar(str) {
return new Set([...str.toLowerCase()]).size !== str.length;
}
In this example I split the string into an array then loop over each element of the array. I stored the previous character in the last variable.
function repeatChar(str) {
let last = '';
for (const char of str.toLowerCase().split('')) {
if (char === last) {
return true;
}
last = char;
}
return false;
}
console.log(repeatChar('aA'));
str.toLowerCase() will not change str
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 run:
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
And I get an array like:
["27","-","28","August","663","CE"]
How would I iterate with that array and loop it to find if an object is a text string or a number?
To be perfectly correct, these are all of the type string, because they are between quotes. I guess you want to find out if these strings can be converted to a number. You can check this with isNan(), gives false when numeric and true when not. You can actually convert the string to a number (integer) with parseInt();
var array = ["27","-","28","August","663","CE"];
for (var el of array) {
if(!isNaN(el)) { // check if el is numeric
el = parseInt(el); // parse el to a int
console.log("This element is numeric");
console.log(el);
}
}
You can use the jQuery $.isNumeric() inside a $.each loop
$.each(words,function(){
if($.isNumeric(this)) {
//code to execute if number
}
})
You can use Number(), which returns NaN if string is non-numeric. One thing to keep in mind is that Number('') === 0.
for (const word of words.split(' ')) {
if (isNaN(Number(word)) {
//code if non-numeric
}
else {
//code if numeric
}
}
you can use Number() directly
var arr = ["0","-","28","August","663","CE"]
function isNumber(str) {
return str && isNaN(Number(str)) ? false : true
}
arr.forEach((item) => {
console.log(isNumber(item))
})
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length; i++) {
console.log(/\d+/g.test(words[i])); // RegExp way (possible only with input formatted like string you specified)
console.log(/^[\d]+(.[\d]+)*$/g.text(words[i])); // RegExp way that would consider floats, ints as a number and would not consider strings like "123aaa" as a number
console.log(!isNaN(parseInt(words[i]))); // NaN with parseInt way
console.log(!isNaN(words[i])); // only NaN way - warning: strings like "123aaa" are considered as a number as parseInt would create an int
with vale of 123
console.log(!isNan(Number(words[i])) && words[i] !== ''); // csadner's solution with Number
// all above logs will output true if the string is a number
}
This should probably solve the problem. What's going on here is:
Regular expression checks if provided string contains only the numbers
parseInt will return NaN (Not a Number) on fail, so we check if the returned value is not NaN.
isNaN itself checks if string is a number - in case you don't want to have hexadecimals, etc.
In the for loop you already have, you can determine if it's NOT a number with this condition:
!words[i] || isNaN(words[i])
If that is true, it's not a number
I am still rather new to JavaScript and I am having an issue of getting the first character of the string inside the array to become uppercase.
I have gotten to a point where I have gotten all the texted lowercase, reversed the text character by character, and made it into a string. I need to get the first letter in the string to uppercase now.
function yay () {
var input = "Party like its 2015";
return input.toLowerCase().split("").reverse().join("").split(" ");
for(var i = 1 ; i < input.length ; i++){
input[i] = input[i].charAt(0).toUpperCase() + input[i].substr(1);
}
}
console.log(yay());
I need the output to be "partY likE itS 2015"
Frustrating that you posted your initial question without disclosing the desired result. Lots of turmoil because of that. Now, that the desired result is finally clear - here's an answer.
You can lowercase the whole thing, then split into words, rebuild each word in the array by uppercasing the last character in the word, then rejoin the array:
function endCaseWords(input) {
return input.toLowerCase().split(" ").map(function(item) {
return item.slice(0, -1) + item.slice(-1).toUpperCase();
}).join(" ");
}
document.write(endCaseWords("Party like its 2015"));
Here's a step by step explanation:
Lowercase the whole string
Use .split(" ") to split into an array of words
Use .map() to iterate the array
For each word, create a new word that is the first part of the word added to an uppercased version of the last character in the word
.join(" ") back together into a single string
Return the result
You could also use a regex replace with a custom callback:
function endCaseWords(input) {
return input.toLowerCase().replace(/.\b/g, function(match) {
return match.toUpperCase();
});
}
document.write(endCaseWords("Party like its 2015"));
FYI, there are lots of things wrong with your original code. The biggest mistake is that as soon as you return in a function, no other code in that function is executed so your for loop was never executed.
Then, there's really no reason to need to reverse() the characters because once you split into words, you can just access the last character in each word.
Instead of returning the result splitting and reversing the string, you need to assign it to input. Otherwise, you return from the function before doing the loop that capitalizes the words.
Then after the for loop you should return the joined string.
Also, since you've reverse the string before you capitalize, you should be capitalizing the last letter of each word. Then you need to reverse the array before re-joining it, to get the words back in the original order.
function yay () {
var input = "Party like its 2015";
input = input.toLowerCase().split("").reverse().join("").split(" ");
for(var i = 1 ; i < input.length ; i++){
var len = input[i].length-1;
input[i] = input[i].substring(0, len) + input[i].substr(len).toUpperCase();
}
return input.reverse().join(" ");
}
alert(yay());
You can use regular expression for that:
input.toLowerCase().replace(/[a-z]\b/g, function (c) { return c.toUpperCase() });
Or, if you can use arrow functions, simply:
input.toLowerCase().replace(/[a-z]\b/g, c => c.toUpperCase())
Here's what I would do:
Split the sentence on the space character
Transform the resulting array using .map to capitalize the first character and lowercase the remaining ones
Join the array on a space again to get a string
function yay () {
var input = "Party like its 2015";
return input.split(" ").map(function(item) {
return item.charAt(0).toUpperCase() + item.slice(1).toLowerCase();
}).join(" ");
}
console.log(yay());
Some ugly, but working code:
var text = "Party like its 2015";
//partY likE itS 2015
function yay(input) {
input = input.split(' ');
arr = [];
for (i = 0; i < input.length; i++) {
new_inp = input[i].charAt(0).toLowerCase() + input[i].substring(1, input[i].length - 1) + input[i].charAt(input[i].length - 1).toUpperCase();
arr.push(new_inp);
}
str = arr.join(' ');
return str;
}
console.log(yay(text));
Try using ucwords from PHP.js. It's quite simple, actually.
String.prototype.ucwords = function() {
return (this + '')
.replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
return $1.toUpperCase();
});
}
var input = "Party like its 2015";
input = input.charAt(0).toLowerCase() + input.substr(1);
input = input.split('').reverse().join('').ucwords();
input = input.split('').reverse().join('');
Note: I modified their function to be a String function so method chaining would work.
function yay(str)
{
let arr = str.split(' ');
let farr = arr.map((item) =>{
let x = item.split('');
let len = x.length-1
x[len] = x[len].toUpperCase();
x= x.join('')
return x;
})
return farr.join(' ')
}
var str = "Party like its 2015";
let output = yay(str);
console.log(output) /// "PartY likE itS 2015"
You can split and then map over the array perform uppercase logic and retun by joining string.
let string = "Party like its 2015";
const yay = (string) => {
let lastCharUpperCase = string.split(" ").map((elem) => {
elem = elem.toLowerCase();
return elem.replace(elem[elem.length - 1], elem[elem.length - 1].toUpperCase())
})
return lastCharUpperCase.join(" ");
}
console.log(yay(string))