Take the first letters of a string splitted by white space [duplicate] - javascript

This question already has answers here:
Get first letter of each word in a string, in JavaScript
(20 answers)
Closed 4 years ago.
I have a string like this:
DEBIT CARD. How can I extract the first letters of this string which is splitted by white space? To be more specific, I want the D and C parts of this string.

Use charAt(0) along with split():
split(/\s+/) will split the string into array structure based on whitespaces(single or multiple) so that you can loop over the elements of the array using map() and get the first character for each element. Then, finally you need to join('') the array and get the string representation.
var str = 'DEBIT CARD';
var res = str.split(/\s+/).map(x=>x.charAt(0)).join('');
console.log(res);

var stringg = 'DEBIT CARD';
var out = stringg.split(' ');
var required = out[1][0]; /* it will return only `C`, if you want the
first character of all letters just loop on `out` and get 0 index,
Here you can also use each loop or map and join functions to
achieve desired output.*/
console.log(required);

Related

Javascript split with regular expression return empty values [duplicate]

This question already has answers here:
javascript regex split produces too many items
(4 answers)
Closed 3 years ago.
Hi I have to split a string in two parts, the first one is always a char the second one is a number.
i.e.
a12
c4
I try to use this expression:
var myString = 'a12';
var mySplits = myString.split(/^([a-zA-Z]{1,2})([0-9]{1,2})$/);
console.log(mySplits);
the array expected is:
["a", "12"]
the result instead is:
["", "a", "12", ""]
I don't understand the reason why the result array has an empty value at start and at end.
Any help is really appreciated.
UPDATE
the solution proposed works but we can use a more elegant way.
ES18
With ES18 we could use the group capturing name
var myString = 'a12';
var matches =
/^(?<letter>[a-zA-Z]{1,2})(?<number>[0-9]{1,2})$/.exec(myString).concat();
console.log(matches.groups.letter);
console.log(matches.groups.number);
ES10
ES10 added the method .matchAll() that returns an Iterator, so if the need is not capture a single value but capture globally this method can be useful.
var myString = 'a12 b12 ';
for (const match of myString.matchAll(/(?<letter>[a-zA-Z]{1,2})(?<number>[0-9]{1,2})/g)) {
console.log(match.groups.letter);
console.log(match.groups.number);
}
var myString = 'a12';
var list = /^([a-zA-Z]{1,2})([0-9]{1,2})$/.exec(myString).concat();
list.shift(); // remove the first element
console.log(list); //This is the list that you want

Selecting Word from Array of Words in JS [duplicate]

This question already has answers here:
Regex: Match desired chars at the beginning/end of string
(1 answer)
What do ^ and $ mean in a regular expression?
(2 answers)
Closed 3 years ago.
I want to select some words out of an array of words.
For example, the array is like below:
var list = ['Brothers', 'Browsers', 'Dermatologist','Specialist','Optometry']
I use below script to perform selection
var pattern = "Der";
var matched = list.filter(a => a.indexOf(pattern) >= 0);
The matched variable will contains:
['Dermatologist']
But when I change the pattern variable value to "ist" the result would be
['Dermatologist','Specialist']
I want my filtering to works only matching from the beginning of every word. So if I set pattern variable value to "Bro" it will returns
['Brothers','Browsers']
But when I set pattern variable value to "ers" it will returns empty array
[]
Can anybody help?
You can simply use startsWith
var list = ['Brothers', 'Browsers', 'Dermatologist','Specialist','Optometry']
var pattern = "Der";
var matched = list.filter(a => a.startsWith(pattern));
console.log(matched)
You can use a regex with ^ (which means beginning of line) before the pattern:
var list = ['Brothers', 'Browsers', 'Dermatologist','Specialist','Optometry'];
var pattern = /^Bro.*/;
var matched = list.filter(a => pattern.test(a));
console.log(matched);

Getting strings between two specific occurrences of specific characters in JS

I am working on the following code. How can I extract/get strings between to specific numbers of characters in an string like
lorem1-lorem9-lorem3-lorem8-lorem1-lorem11-one-two-three-lorem22-lorem55.png?
What I need is:
one-two-three
I am able to remove things after the 9 occurrence of the - but not sure how to remove things before the 6 occurrence of - as well
var str = "lorem1-lorem9-lorem3-lorem8-lorem1-lorem11-one-two-three-lorem22-lorem55.png"
console.log(str.split("-", 9).join("-"));
Array.prototype.splice can be used to split an array.
var str = "lorem1-lorem9-lorem3-lorem8-lorem1-lorem11-one-two-three-lorem22-lorem55.png"
let out = str.split("-", 9).splice(6).join("-")
console.log(out);

Tricky RegEx Capture [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 6 years ago.
I've got a couple strings and I need to pull characters out that appear between double quotes. The problem is, I want to grab them in groups.
var str = 'FF\"J"A4"L"';
var results = str.match(/\"(.*)\"/);
This returns everything between the first and last double quote. In this case it returns J"A4"L but what I need it to return is J and L.
The content between quotes is pretty much any unicode character like letters and numbers including as }, =, and #.
Any ideas on how to complete this with regex?
It sounds like the content between quotes is any character except for a quote, in which case you can get away with
/"([^"]*)"/
what you're looking for is this with the /g "global flag":
/("[^"]*")/g
In your example, it's like this:
var str = 'FF\"J"A4"L"';
var results = str.match(/("[^"]*")/g);
When doing this, results would be [""J"", ""L""], which contains the entire match (which is why the extra quotes are there).
If you wanted just the matched groups (which returns just the groups, not the whole match area), you would use exec:
var str = 'FF\"J"A4"L"';
var results = []
var r = /("[^"]*")/g
match = r.exec(str);
while (match != null) {
results.push(match[1])
match = r.exec(str);
}
Now, results is ["J", "L"]

replace Nth occurence in string - JavaScript [duplicate]

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 9 years ago.
I'm sure this was supposed to work, but I can't get it doing what I want it to:
new_str = old_str.replace(3, "a");
// replace index 3 (4th character) with the letter "a"
So if I had abcdef then above should return abcaef but I must have gotten something wrong. It is changing characters, but not the expected ones.
Either native JS or jQuery solution is fine, whatever is best (I'm using jQuery on that page).
I've tried searching but all tutorials talk of Regex, etc. and not the index replace thing.
You appear to want array-style replacement, so convert the string into an array:
// Split string into an array
var str = "abcdef".split("");
// Replace char at index
str[3] = "a";
// Output new string
console.log( str.join("") );
Here are three other methods-
var old_str= "abcdef",
//1.
new_str1= old_str.substring(0, 3)+'a'+old_str.substring(4),
//2.
new_str2= old_str.replace(/^(.{3}).(.*)$/, '$1a$2'),
//3.
new_str3= old_str.split('');
new_str3.splice(3, 1, 'a');
//return values
new_str1+'\n'+new_str2+'\n'+ new_str3.join('');
abcaef
abcaef
abcaef

Categories

Resources