JS : Remove all strings which are starting with specific character - javascript

I have an array contains names. Some of them starting with a dot (.), and some of them have dot in the middle or elsewhere. I need to remove all names only starting with dot. I seek help for a better way in JavaScript.
var myarr = 'ad, ghost, hg, .hi, jk, find.jpg, dam.ark, haji, jive.pdf, .find, home, .war, .milk, raj, .ker';
var refinedArr = ??

You can use the filter function and you can access the first letter of every word using item[0]. You do need to split the string first.
var myarr = 'ad, ghost, hg, .hi, jk, find.jpg, dam.ark, haji, jive.pdf, .find, home, .war, .milk, raj, .ker'.split(", ");
var refinedArr = myarr.filter(function(item) {
return item[0] != "."
});
console.log(refinedArr)

Use filter and startsWith:
let myarr = ['ad', 'ghost', 'hg', '.hi', 'jk'];
let res = myarr.filter(e => ! e.startsWith('.'));
console.log(res);

You can use the RegEx \B\.\w+,? ? and replace with an empty String.
\B matches a non word char
\. matches a dot
\w+ matches one or more word char
,? matches 0 or 1 ,
[space]? matches 0 or 1 [space]
Demo:
const regex = /\B\.\w+,? ?/g;
const str = `ad, ghost, hg, .hi, jk, find.jpg, dam.ark, haji, jive.pdf, .find, home, .war, .milk, raj, .ker`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);

Related

Capture only letter followed by letter, excluding some words - Regex

I need to capture a letter in a string followed by a letter, excluding some specific words. I have the following string in Latex:
22+2p+p^{pp^{2p+pp}}+\delta+\pi+sqrt(2p)+\\frac{2}+{2p}+ppp+2P+\sqrt+xx+\to+p2+\pi+px+ab+\alpha
I want to add * between the letters, but I don't want the following words to apply:
\frac
\delta
\pi
\sqrt
\alpha
The output should be as follows:
22+2p+p^{p*p^{2p+p*p}}+\delta+\pi+\sqrt(2p)+\\frac{2}+{2p}+p*p*p+2P+\sqrt(9)+x*x+\to+p2+\pi+p*x+a*b+\alpha
The letters are dynamic entries, which can be any of the alphabet. I thought about using "positive lookbehind" but its support is limited.
You can achieve the result you want with a string replace with callback, using a regex:
(delta|frac|pi|sqrt|alpha|to)|([a-z](?=[a-z]))
that matches one of the excluded words in group 1 or a letter that is followed by another letter in group 2. In the callback, if group 1 is present, that is returned otherwise group 2 is returned followed by a *:
let str = '22+2p+p^{pp^{2p+pp}}+\\delta+\\pi+\\sqrt(2p)+\\\\frac{2}+{2p}+ppp+2P+\\sqrt(9)+xx+\\to+p2+\\pi+px+ab+\\alpha';
const replacer = (m, p1, p2) => {
return p1 ? p1 : (p2 + '*');
}
console.log(str.replace(/(delta|frac|pi|sqrt|alpha|to)|([a-z](?=[a-z]))/gi, replacer));
You can do something like this:
const str = "22+2p+p^{pp^{2p+pp}}+\\delta+\\pi+\\sqrt(2p)+\\\\frac{2}+{2p}+ppp+2P+\\sqrt+xx+\\to+p2+\\pi+px+ab+\\alpha";
const result = str.replace(/\\?[a-zA-Z]{2,}/g, (v) => {
if (v.startsWith('\\')) {
return v;
}
return v.split("").join("*");
});
console.log(result);
What this does is to match all 2 or more consecutive letters that are preceded by a \ or not and in the replace function, if the matched group is not starting with \, the replacement is set to the letters group split and joined by *.
You could use negative lookbehind to solve this.
const regex = /(?<!\\{1,})(\b[a-zA-Z]{2,}\b)/g;
const str = `22+2p+p^{pp^{2p+pp}}+\\delta+\\pi+\\sqrt(2p)+\\\\frac{2}+{2p}+ppp+2P+\\sqrt+xx+\\to+p2+\\pi+px+ab+\\alpha`;
let m;
let result = str.replace(regex, function(match) {
return match.split("").join("*");
});
console.log("Match: ",str.match(regex).toString());
console.log(result);

Get Initials of full names with accented characters through REGEX

I want to get the initials of a full name even if the name has accents or dots or comma.
If I have the name:
"Raúl, Moreno. Rodríguez Carlos"
I get "RLMRGC".
my code is:
user.displayName.match(/\b[a-zA-Z]/gm).join('').toUpperCase()
I want to get "RMRC". Thanks in advance.
My guess is that this expression might work:
const regex = /[^A-Z]/gm;
const str = `Raúl, Moreno. Rodríguez Carlos`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
Try this (with REGEX):
const data = "Raúl, Moreno. Rodríguez Carlos";
const result = data.match(/\b[A-Z]/gm);
console.log(result);
other solution without REGEX:
const data = "Ędward Ącki";
const result = [...data].filter((c, k, arr) => c !== ' ' && (k == 0 || arr[k-1] == ' ' ))
console.log(result);
A fully Unicode compatible solution should match any letter after a char other than letter or digit.
Here are two solutions: 1) an XRegExp based solution for any browser, and 2) an ECMAScript 2018 only JS environment compatible solution.
var regex = XRegExp("(?:^|[^\\pL\\pN])(\\pL)");
console.log( XRegExp.match("Łukasz Żak", regex, "all").map(function(x) {return x.charAt(x.length - 1);}).join('').toUpperCase() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.2.0/xregexp-all.min.js"></script>
ECMAScript 2018 compliant solution:
// ONLY WORKING IN ECMAScript2018 COMPLIANT JS ENVIRONMENT!
var regex = /(?<![\p{N}\p{L}])\p{L}/gu;
console.log( "Łukasz Żak".match(regex).join('').toUpperCase() );
// => ŁŻ
NOTE:
(?:^|[^\pL\\pN])(\pL) matches start of a string and any char but letter and digit and then matches any letter (since the char matched by the first non-capturing group is not necessary, .map(function(x) {return x.charAt(x.length - 1);}) is required to get the last char of the match)
(?<![\p{N}\p{L}])\p{L} matches any letter (\p{L}) that is not preceded with a digit or letter (see the negative lookbehind (?<![\p{N}\p{L}]))

How to append a string to another string after every N char?

I am trying to create a program that adds "gav" after every second letter, when the string is written.
var string1 = "word"
Expected output:
wogavrdgav
You can use the modulus operator for this -
var string1 = "word";
function addGav(str){
var newStr = '';
var strArr = str.split('');
strArr.forEach(function(letter, index){
index % 2 == 1
? newStr += letter + 'gav'
: newStr += letter
})
return newStr;
}
console.log(addGav(string1)); // gives wogavrdgav
console.log(addGav('gavgrif')) //gives gagavvggavrigavf....
RegEx
Here, we can add a quantifier to . (which matches all chars except for new lines) and design an expression with one capturing group ($1):
(.{2})
Demo
JavaScript Demo
const regex = /(.{2})/gm;
const str = `AAAAAA`;
const subst = `$1bbb`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
RegEx Circuit
You can also visualize your expressions in jex.im:
If you wish to consider new lines as a char, then this expression would do that:
([\s\S]{2})
RegEx Demo
JavaScript Demo
const regex = /([\s\S]{2})/gm;
const str = `ABCDEF
GHIJK
LMNOP
QRSTU
VWXYZ
`;
const subst = `$1bbb`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Try this:
const string1 = 'word'
console.log('Input:', string1)
const newStr = string1.replace(/(?<=(^(.{2})+))/g, 'gav')
console.log('Output:', newStr)
.{2}: 2 any character
(.{2})+: match 2 4 6 8 any character
^(.{2})+: match 2 4 6 8 any character from start, if don't have ^, this regex will match from any position
?<=(regex_group): match something after regex_group
g: match all
This way is finding 2,4,6, etc character from the start of the string and don't match this group so it will match '' before 2,4,6, etc character and replace with 'gav'
Example with word:
match wo, word and ignore it, match something before that('') and replace with 'gav' with method replace

How to process string so to keep characters up to last digit?

Given strings such as G08a, Professor3, Obs...
How to slice these strings after the last digit, so it returns :
G08a ==> G08
Professor3 ==> Professor3
Obs ==> Obs
Starting jsfiddle : https://jsfiddle.net/dpyqg2mk/
You can use a regex for this.
var ss = ["G08a", "Professor3", "Obs"];
var res = ss.map(s => (/^(.*?\d)\D*$/.exec(s) || [,s])[1]);
console.log(res);
This collects all characters up through a digit that is followed by a series of zero or more non-digits that continue to the end of the string. The initial characters and that last digit before the non-digits are captured in a group.
I used .map() as a convenience for the demo, and substituted a temporary array when the regex finds no match.
Short and simple:
let str = "foo9bar";
str = str.match(/(.*\d)|(.*\d?)/g)[0]; // str is now foo9
let elem = document.getElementById('txt');
elem.innerHTML = elem.innerHTML.match(/(.*\d)|(.*\d?)/g)[0];
<p id="txt">foo9bar</p>
First you need to find first digit' position in string
var str = "G08a";
var match = str.match(/(\D+)?\d/)
var index = match ? match[0].length-1 : -1;
Then make substring
var result =str.substring(0,index);
You could match the string by using a search for any character foolowd by a digit or any character which are followed ba a non digit or end of string.
console.log(['G08a', 'Professor3', 'Obs', 'abc123def456ghi'].map(function (s) {
return s.match(/^.*\d|.*(?=\D|$)/)[0];
}));

How to Split string with multiple rules in javascript

I have this string for example:
str = "my name is john#doe oh.yeh";
the end result I am seeking is this Array:
strArr = ['my','name','is','john','&#doe','oh','&yeh'];
which means 2 rules apply:
split after each space " " (I know how)
if there are special characters ("." or "#") then also split but add the characther "&" before the word with the special character.
I know I can strArr = str.split(" ") for the first rule. but how do I do the other trick?
thanks,
Alon
Assuming the result should be '&doe' and not '&#doe', a simple solution would be to just replace all . and # with & split by spaces:
strArr = str.replace(/[.#]/g, ' &').split(/\s+/)
/\s+/ matches consecutive white spaces instead of just one.
If the result should be '&#doe' and '&.yeah' use the same regex and add a capture:
strArr = str.replace(/([.#])/g, ' &$1').split(/\s+/)
You have to use a Regular expression, to match all special characters at once. By "special", I assume that you mean "no letters".
var pattern = /([^ a-z]?)[a-z]+/gi; // Pattern
var str = "my name is john#doe oh.yeh"; // Input string
var strArr = [], match; // output array, temporary var
while ((match = pattern.exec(str)) !== null) { // <-- For each match
strArr.push( (match[1]?'&':'') + match[0]); // <-- Add to array
}
// strArr is now:
// strArr = ['my', 'name', 'is', 'john', '&#doe', 'oh', '&.yeh']
It does not match consecutive special characters. The pattern has to be modified for that. Eg, if you want to include all consecutive characters, use ([^ a-z]+?).
Also, it does nothing include a last special character. If you want to include this one as well, use [a-z]* and remove !== null.
use split() method. That's what you need:
http://www.w3schools.com/jsref/jsref_split.asp
Ok. i saw, you found it, i think:
1) first use split to the whitespaces
2) iterate through your array, split again in array members when you find # or .
3) iterate through your array again and str.replace("#", "&#") and str.replace(".","&.") when you find
I would think a combination of split() and replace() is what you are looking for:
str = "my name is john#doe oh.yeh";
strArr = str.replace('\W',' &');
strArr = strArr.split(' ');
That should be close to what you asked for.
This works:
array = string.replace(/#|\./g, ' &$&').split(' ');
Take a look at demo here: http://jsfiddle.net/M6fQ7/1/

Categories

Resources