how to get first character of second string in javascript? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 months ago.
Improve this question
how to get first 2 character of string in javascript like this "Hello world " => get this "wo"?
another example
"Osama Mohamed" => M.

you can use string.split(' '), this function will split you string into an array, for example:
let s = "Hello World";
console.log(s.split(" ")) // will log ["Hello", "World"]
then you can get the second word using array[index] when index the index of your desired word in said array.
now using string charAt we can get the first letter of the word.
now to put everything together:
let s = "Hello World"
let s_splited = s.split(" ") // ["Hello", "World"]
let second_word = s_splited[1]
console.log(second_word.charAt(0))

string = "Hello world";
split_string = string.split(" ");
second_word = split_string[1]
first_char = second_word[0]
console.log(first_char)
OR
string = "Hello world";
console.log(string.split(" ")[1][0])

Related

split method to return only values split by a comma not quotes in comma [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 days ago.
Improve this question
I want to split the string below by a default comma which is , and ignore the "," part.
Has anyone come up with a solution for this? Tried a bunch of solutions, but doesn't work.
My string: (testing","a framework), hello world, testing","antother_framework
expected result:
["testing","a framework", "hello world", "testing","antother_framework]
not the nicest way, with regex you could grouped the replace but it works
const str = '(testing","a framework), hello world, testing","antother_framework';
let arr = str.split(',');
console.log(arr);
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll('(', '');
arr[i] = arr[i].replaceAll(')', '');
arr[i] = arr[i].replaceAll('\"', '');
arr[i] = arr[i].trim();
}
console.log(arr);
You could use this function:
function splitByCommas(str) {
return str.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/);
}
Explanation:
/,(?=(?:[^"]"[^"]")[^"]$)/ -> match the comma outside of the quotes
(?:[^"]"[^"]")* -> match the quotes and the text inside the quotes
[^"]*$ -> match the remaining text after the last quote
If you run the function like this:
console.log(splitByCommas('(testing","a framework), hello world, testing","antother_framework'));
It will give the following output:
[
'(testing","a framework)',
' hello world',
' testing","antother_framework'
]
If you want to also trim the whitespaces, you can use this:
function splitByCommas(str) {
return str.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(function (item) {
return item.trim();
}
);
}
For the same input giving you:
[
'(testing","a framework)',
'hello world',
'testing","antother_framework'
]

Extracting a string from another string Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have this particular string :
TOYIN KEMIOGS/OYO/2277TGOGSLAGOS
from this string containing 2 '/'
I want it to extract from wherever we have OGS and stop at wherever we have OGS. OGS always start and end my extracted string
I want an extracted result like this
OGS/OYO/2277TGOGS
Thanks so much
You can achieve it but as a string between first occurrence and last occurrence of OGS as follows:
var a = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
console.log(a.slice(a.indexOf("OGS"),a.lastIndexOf("OGS")) +"OGS");
You can use match method of string to extract the data required.
const str = "TOYIN KEMIOGS/OYO/2277TGOGSLAGOS";
const result = str.match(/OGS.*OGS/); // Its greedy in nature so you can also use /OGS.*?OGS/
console.log(result[0]);
let str = "TOYIN KEMIOGS/OYO/2277TGOGSLAGOS";
let phrase = "OGS";
let start = str.indexOf(phrase);
let end = str.lastIndexOf(phrase) + phrase.length;
let newStr = str.slice(start, end);
console.log(newStr);
You can treat the start/stop sequences as non-matching groups:
const str = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
const [match] = str.match(/(?:OGS).+(?:OGS)/);
console.log(match); // "OGS/OYO/2277TGOGS"
If you don't want to keep the start/stop sequences ("OGS"), you can treat them as positive lookbehind/lookaheads:
const str = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
const [match] = str.match(/(?<=OGS).+(?=OGS)/);
console.log(match); // "/OYO/2277TG"
Here is a string manipulation version, which captures the first and last index.
const extractBetween = (str, marker) =>
str.slice(str.indexOf(marker),
str.lastIndexOf(marker) + marker.length);
const str = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
const match = extractBetween(str, 'OGS');
console.log(match); // "OGS/OYO/2277TGOGS"

Print all the characters separated by a space js [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
i have a variable and I want to separate the name whit a space letter by letter and then UpperCase the letters
var name = "Tom Hanks";
console.log(name) has to be equal to "T O M H A N K S"
var name = "Tom Hanks";
var result = name.toUpperCase().split("").join(" ").replace(/\s+/g, " ");
console.log(result);
First you must split the string to separate the letters of the word and save 'em in a array object. For that you can use the String.split() function:
const myString = 'Tom Hanks';
const splittedString = myString.split('');
Then you can use Array.join() function to create a new string with spaces between the letters of the previous array:
const stringWithSpaces = splittedString.join(' ');
Finally you can use the String.toUpperCase() to set the "caps lock" on:
stringWithSpaces.toUpperCase();
So, here is the complete snippet:
const myString = 'Tom Hanks';
const splittedString = myString.split('');
const stringWithSpaces = splittedString.join(' ');
const upperCaseStringWithSpaces = stringWithSpaces.toUpperCase();
console.log(upperCaseStringWithSpaces);

JavaScript - check string for substring and capitalize substring [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How would I test a string to see if it contains a specific substring and then capitalize that substring?
var string = " A Fine and Rare George Iii Neoclassical Ormolu Urn Clock"
And find and capitalize the Roman numeral to III.
Another example:
var string2 = "Platinum Pf00673"
Find and capitalize letters in strings that contain numbers, so the above becomes PF00673
You can make use of the callback to String#replace.
var string2 = "Platinum Pf00673";
var result = string2.replace(/\w*[0-9]\w*/g, match=>match.toUpperCase());
console.log(result);
Use regex to match and replace.
var string2 = "Platinum Pf00673"
var reg = new RegExp("[A-Z]+[0-9]+[A-Z0-9]+", "gi");
var matches = string2.matchAll(reg);
for(var match of matches)
{
var parts = string2.split("");
parts.splice(match.index, match[0].length, ...match[0].toUpperCase().split(""));
string2 = parts.join("");
}
console.log(string2);
A simple solution could be to create a helper function like so
const capitlizeSubStr = (string, substring) => {
const regex = new RegExp(substring, 'gi')
const newString = string.replace(regex, substring.toUpperCase())
return newString
}
Answering for the Roman Numeral question.
var string1 = "A Fine and Rare George Iii Neoclassical Ormolu Urn Clock";
var result = string1.replace(/M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})/ig, match=>match.toUpperCase());
console.log(result);
It's an extension of hev1's answer.
capitalize romans:
'world war Iii'.replace(/\w+/g, word => word.match(/^[MCDXVI]+$/i) ? word.toUpperCase() : word)
// "world war III"
capitalize words with digits
'Platinum Pf00673'.replace(/\w+/g, word => word.match(/\d/) ? word.toUpperCase() : word)
// "Platinum PF00673"

Ho do I split these 2 string using Regex? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Following are 2 strings:
" at callback (/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js:541:21)"
" at /Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js:269:22"
How do I split them to these using JS and Regex?
['callback', '/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js', '541', '21']
['', '/Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js', '269', '22']
try regexp named groups
https://github.com/tc39/proposal-regexp-named-groups
it adds result readability for such strange regexes ;)
const strings = [
" at callback (/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js:541:21)",
" at /Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js:269:22"
];
const regex = /^\s*?at\s?(?<source>.*?)\s\(?(?<path>.*?):(?<row>\d*):(?<column>\d*)/;
strings.forEach(string => {
const result = string.match(regex);
resultElement.innerHTML +=
'\n' + JSON.stringify({string, "result.groups": result.groups}, null, 4)
})
<pre id="resultElement"/>
You can use regex for such purpose, i.e:
const regex = /at( (?:[a-z]+)?)\(?(.+)\:(\d+)\:(\d+)\)?/;
//const str = " at callback (/Users/lem/Projects/RingAPI/packages/server/node_modules/loopback-connector-rest/lib/rest-builder.js:541:21)";
const str = " at /Users/lem/Projects/RingAPI/packages/server/node_modules/#loopback/repository/node_modules/loopback-datasource-juggler/lib/observer.js:269:22";
const found = str.match(regex);
found.splice(0, 1)
console.log(found)
It works for both strings!
I've wrote simple parse function for you:
function parse(string) {
const functionName = string.match(/at .* /);
return [
...(functionName && [functionName[0].slice(2).trim()] || ['']),
...string.match(/\/.*/)[0].split(':')
];
}
First of all I try to extract function name. If it exists I remove 'at' word and use trim function to remove unnecessary spaces. Then I look for substring beginning with slash '/' and match every character after it. Last step is to split returned string.
I believe it matches your requirements.
I've also prepared demo in stackblitz: https://stackblitz.com/edit/js-ol22yf

Categories

Resources