How to take first character from 2 words - javascript

I have input = "Graha Cinere". And I want the output just "GCi". So G it's take from first characters in first words and Ci from second words.
val = "Graha Cinere"
val.match(/\b(\w)/g).join('')
Current output : GC
Expected Output : GCi
I wish there's an answer from my question.

Here's a couple of ways to do this. Firstly you can use a regex to match the single character at the start of the first word and two characters at the start of the second word and then join those parts.
val = "Graha Cinere";
out = val.match(/^(\w)\w*\s+(\w{1,2})/).slice(1).join('');
console.log(out);
Secondly you could split the string on space and then take the first character of the first result and the first two characters of the second result and join them:
val = "Graha Cinere";
out = val.split(' ').map((v, i) => v.slice(0, i+1)).join('');
console.log(out);

first split then take two words
val = "Graha Cinere";
parts = val.split(" ");
neededStr = parts[0][0] +parts[1][0]+ parts[1][1];
console.log(neededStr);
Also, You can use String slice
let val = "Graha Cinere";
let parts = val.split(" ");
neededPartOne = parts[0][0];
neededPartTwo = parts[1].slice(0,2);
exactNeeded = neededPartOne + neededPartTwo;
console.log(exactNeeded);

Hello Bai!
Although the use of Regex is extremely useful and practical for this and some other situations with more complex scenarios, I would recommend you to first take a look and give a try to the native string methods coming along with most languages, that will give ya a better scope of what you can do with the language itself to find a prompt solution to your cases and if not, then you go to the next step by getting the extra help from some other tools such as RegEx, Underscore or its successor Lodash just to name a few:
I put this small snippet of JS together for you to take a look at a simpler way to handle this case. This is not the only way to do it, but it is merely made in the language in use.
Cheers, pal!
let str="Graha Cinere";
(() => {
return str.charAt(0).concat(str.substr(str.indexOf(' ')+1,2));
})();

this will give you what you're looking for-
val.split(" ")[0][0] + val.split(" ")[1][0]

Related

Javascript regular expression to sanitize string with pipes

I need a little help in trying to sanitize a string. I have written a regular expression that is pretty close to giving me the results I want but I just can't quite get it right. The string I'm receiving is in this format.
||a|assa||asss||ssss
The pipe character are basically placeholders to what would have been a separator for text. However, I'm trying to end up with something that would look like this.
|a|b|c|d in other words I'm just trying to remove consecutive pipes. I have put together a little example to illustrate what I have attempted and keep failing miserably.
const str1 = "||a||jump|fences||in the street";
const str2 = "im a wolf";
const hasPipe = /\|{1}\+/;//if the | is consecutevely repeated more than once than deleted.
console.log(hasPipe.test(str1));
console.log(str1.replace(hasPipe, ""))
console.log(hasPipe.test(str2));
The expected result to the above code should simply be.
|a|jump|fences|in the street"
Can someone please point me in the right direction or point my silly mistake.
Given your test string const str1 = "||a||jump|fences||in the street"; you want to replace multiple occurrences of pipe | with a single pipe.
There are a couple of ways to match a non-empty sequence:
+ = match 1 or more of the previous expression
{n,m} = match at least n but not more than m occurrences.
{n,} = match at least n and unlimited times.
Simple:
str1.replace(/\|+/g, "|")
"|a|jump|fences|in the street"
Matches one or more pipes and replaces with a single pipe. This replaces a single pipe with a pipe.
More exact:
str1.replace(/\|{2,}/g, "|")
"|a|jump|fences|in the street"
Matches two or more (because there is no max after the comma) pipes and replaces with a single pipe. This does not bother replacing a single pipe with another single pipe.
There are also a couple of ways to match exactly two pipes, if you'll never have a run of 3 or more:
str1.replace(/\|\|/, "|");
str1.replace(/\|{2}/, "|");
Not much to it:
\|\|+ replace with |
https://regex101.com/r/vvkrI0/1/
You can use the + to find all the locations that have 1 or more pipes in a row, and replace them all with a single pipe. Your regex would simply be:
/\|+/g
Here is an example, with a variable number of pipes:
const str1 = "||a|||jump|fences||||in the street";
var filtered_str1 = str1.replace(/\|+/g,"|")
console.log(filtered_str1);
You could substitute consective pipe characters like this:
const pat = /\|{2,}/gm;
const str = `||a|||jump|fences||in the street`;
const sub = `|`;
const res = str.replace(pat, sub);
console.log('result: ', res);
Result:
|a|jump|fences|in the street

Regex - Capture anything within parentheses and brackets

I'm really bad at regex and I'm not sure what to do with this. I want to capture anything within () or [] (including the brackets) and nothing after. For example if I type [this is text] I want it to return exactly that. Also I have a json full of terms the user types. If the term is not on the json then it shouldn't print. This is the snippet of code which relates to the regex.
let sf_re = /(?:(,)\s+|\s+(xx)\s+)|\+|(,)/
if (document.querySelector(".images")){
document.querySelector(".images").innerHTML = ""
for(var i=0;i<item.length;i++){
if(/(\[(.*?)\]|\((.*?)\))/.test(item[i])){
let text = item[i]
let note = document.createElement("span")
note.innerHTML = String(text)
document.querySelector(".images").appendChild(note)
}
Here is an example of what happens
The only thing that should show is [cat cat cat]. "dog" should not appear at all because it's not on my list. In regexr it seems to work fine. I'm not sure what to add.
Edit: I think that my original post had insufficient information. The user types into an input bar which is split into an array using .split(). My main goal is to allow the user to add small lines of text. For example if my json has the terms "cat", "dog", and "pig" and the user types those terms, then it will return something. This is what I get using the suggestions below. Notice how "f" returns an arrow the first time, but not the second time. I'm not sure why this happens. I may be using "match" wrong. I tried this and I get an error "cannot read property of undefined":
let regex = /(\[(.*?)\]|\((.*?)\))/
if (document.querySelector(".images")){
document.querySelector(".images").innerHTML = ""
for(var i=0;i<item.length;i++){
if(item[i].match(regex)[0]){
let text = item[i]
let note = document.createElement("span")
note.innerHTML = String(text)
document.querySelector(".images").appendChild(note)
}
Also I have a json full of terms the user types. If the term is not on the json then it shouldn't print.
You can use
obj.hasOwnProperty(prop);
This will let you know whether the object contains the specified prop. Here is an Example -
var x = {
y: 10
};
alert(x.hasOwnProperty("y")); //true
alert(x.hasOwnProperty("z")); //false
The regex is [\[|\(](.*)[\]\)]
Explanation: read '[' or '(', then read anything until there is a ']' or a ')'
var regexp = /[\[|\(](.*)[\]\)]/;
var match = ("[cat cat cat]dog").match(regexp);
console.log(match[1]);
Here are two simple regexs you can use. One matches on brackets and the other matches on parenthesis.
The third is a combination that checks for either. Keep in mind, however, that you'll only ever be able to one of each for [ ] and ( ). If you're accepting multiple of either kind, then the regex will break since it'll return all characters between the outermost ones.
Using match it gives back an array, so if you know you're only getting a single result, you can grab the first item, like in result and result2. If not, you can just deal with the array of results like in result3.
const regex = /\[.*\]/
const regex2 = /\(.*\)/
const regex3 = /(\[.*\])|(\(.*\))/g
const result = ("[cat cat cat]dog").match(regex3)[0];
const result2 = ("banana(cat cat)horse").match(regex3)[0];
const result3 = ("alfred[cat cat cat]banana(dog dog)").match(regex3);
console.log(result); //[cat cat cat]
console.log(result2); //(cat cat)
console.log(result3); // [ '[cat cat cat]', '(dog dog)' ]
The . character matches anything, and the * will repeat 0 or more times. The \ character can be used to escape [, ], ( and ) as necessary (and any other special regex character). The g at the end will check across the entire string.
Hopefully that should be enough to get you un-stuck.

JS Regex: how to remove first 2 zero's from "08/08/2017"

I'm new to regex, and have been researching all night how to remove the first 2 zeros from a string like "08/08/2017" (without removing 0 in "2017")
The 5+ regex tutorials I've reviewed do not seem to cover what I need here.
The date could be any sysdate returned from the system. So the regex also needs to work for "12/12/2017"
Here is the best I have come up with:
let sysdate = "08/08/2017"
let todayminuszero = str.replace("0","");
let today = todayminus0.replace("0","");
It works, but obviously it's unprofessional.
From the tutorials, I'm pretty sure I can do something along the lines of this:
str.replace(/\d{2}//g,""),);
This pattern would avoid getting the 3rd zero in str.
Replacement String would have to indicate 8/8/
Not sure how to write this though.
For date manipulation I would use other functions(best date related) but, this should do it, for the case that you stated. If you need other formats or so, I would suggest removing the zeros in an different way, but It all depends on you UseCase.
let sysdate = "08/08/2017";
let todayminuszero = sysdate.replace(/0(?=\d\/)/gi,"");
console.info(todayminuszero);
(?= ... ) is called Lookahead and with this you can see what is there, without replacing it
in this case we are checking for a number and a slash. (?=\d\/)
here some more information, if you want to read about lookahead and more http://www.regular-expressions.info/lookaround.html
A good place to test regex expressions is https://regex101.com/
I always use this for more advance expressions, since it displays all matching groups and so, with a great explaination. Great resource/help, if you are learning or creating difficult Expressions.
Info: as mentioned by Rajesh, the i flag is not needed for this Expression, I just use it out of personal preference. This flag just sets the expression-match to case insensitive.
-- Out of Scope, but may be interesting --
A longer solution without regex could look like this:
let sysdate = "08/08/2017";
let todayminuszero = sysdate.split("/").map(x => parseInt(x)).join("/");
console.info(todayminuszero);
Backside, this solution has many moving parts, the split function to make an array(´"08/08/2017"´ to ´["08", "08", "2017"]´), the map function, with a lambda function => and the parseInt function, to make out of each string item a nice integer (like: "08" to 8, ... ) and at last the join function that creates the final string out of the newly created integer array.
you should use this
let sysdate = "08/08/2017"
let todayminuszero = sysdate.replace(/(^|\/)0/g,"$1");
console.log(todayminuszero);
function stripLeadingZerosDate(dateStr){
return dateStr.split('/').reduce(function(date, datePart){
return date += parseInt(datePart) + '/'
}, '').slice(0, -1);
}
console.log(stripLeadingZerosDate('01/02/2016'));
console.log(stripLeadingZerosDate('2016/02/01'));
look at here
function stripLeadingZerosDate(dateStr){
return dateStr.split('/').reduce(function(date, datePart){
return date += parseInt(datePart) + '/'
}, '').slice(0, -1);
}
console.log(stripLeadingZerosDate('01/02/2016'));// 1/2/2016
console.log(stripLeadingZerosDate('2016/02/01'));// "2016/2/1"
By first 2 zeros, I understand you mean zero before 8 in month and in date.
You can try something like this:
Idea
Create a regex that captures group of number representing date, month and year.
Use this regex to replace values.
Use a function to return processed value.
var sysdate = "08/08/2017"
var numRegex = /(\d)+/g;
var result = sysdate.replace(numRegex, function(match){
return parseInt(match)
});
console.log(result)

How to store only the nth substring into a variable in Javascript

var a="how are you?";
In the above example I want to store the second word "are" into another variable in a single step.
I don't want to use something like below
var bigArray = a.split(" ");
var secondText = bigArray[1];
as we may need to store the entire paragraph into a big array and consume a lot of memory without any use.
I would like to know if there is some function which works as below
var secondText=specialFunction(a," ",1);
so that we will get the second substring when the paragraph is split by " "
Well, I would spend my time worrying about more important things than the size of some arrays.
Anyway, you could try using a regexp:
var secondText = (a.match(/ (\w+)/) || []) [1];
This reads as "find a space, then capture the following word".
The || [] part is meant to deal with the situation where there is no match (for example, no second word). In that case, the result will be [][1] which is undefined.
This finds only the second word. What about the more general case? Since we are not allowed to split the string on spaces, because that would create an array and the OP doesn't want that due to memory concerns. So, we will instead build a dynamic regexp. To find the nth word, we want to skip over the first n-1 spaces. Or, to be more precise, we want to skip over the first word, some spaces, then the second word, then some more spaces, etc. So the regexp is
/(?:\w+ ){n}(\w+)/
^^ NO CAPTURING GROUP
^^^^ WORD FOLLOWED BY SPACE
^^^ N TIMES
^^^^^ CAPTURE FOLLOWING WORD
The ?: is to avoid this being treated as a capturing group. We build the regexp using
function make_nth_word_regexp(n) {
n--;
return new RegExp("(?:\\w+ ){" + n + "}(\\w+)");
}
Now look for your nth word:
var fifth_word = str.match(make_nth_word_regexp(5)) [1];
> "Hey there you".match(make_nth_word_regexp(3))[1]
< "you"
Alternative to regex is just to use substring(). Something like
var a="how are you";
alert(a.substring(a.indexOf(" "), a.length).substring(0, a.indexOf(" ")+1));

Regex .exec into array

I want to capture some values in a string, THEN return them to the page. Here is an example of the code. As I understand, the .exec should store the values it matches into the array correct? This should return Savage, Betsy. Can someone enlighten me on to what's wrong?
var regex = /\b(Betsy)(Savage)\b/i;
var string = "My friend is Betsy Ann Savage";
var arrayMatch = null;
while(arrayMatch = regex.exec(string)){
document.getElementById("text").innerHTML = arrayMatch[1] + ", " + arrayMatch[0];
}
You don't get any matches like this. You could add .* between (Betsy) and (Savage)...
It sounds like you think \b(Besty)(Savage)\b will match EITHER Besty, OR Savage, but that isn't the case. It's looking for one string where both parts are combined - you might as well try to match \b(BetsySavage)\b. This is because a while yes, you do have two groups separated by parentasis, you have them directly next to each other, so the Regex engine says, 'okay', I'll look for both right next to each other. I think what you really want to do is use | which represents an OR. As in \b(Besty|Savage)\b.

Categories