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

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

Related

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}]))

Replacement by matching in Javascript

I need to match numbers followed by a unit and replace them with digits+underscore+unit using Javascript.
I came out with this code, which does not produce the result I am seeking to achieve.
var x = myFunction("I have 3 billion dollars");
function myFunction(text) {
return text.replace(/(\d+\.?(?:\d{1,2})?) (\bmillion\b|\bbillion\b|\bbillion\b|\bmillions\b|\bbillions\b|\btrillion\b|\btrillions\b|\bmeter\b|\bmeters\b|\bmile\b|\bmiles\b|\%)/gi, function (match) {
return "<span class='highlighted'>" + match[1] + "_" + match[2] + "</span>";
});
}
The above code should return "I have 3_billion dollars" (but it returns _b as far as the substitution is concerned). As I am a newbe with Java, any suggestions would be appreciated.
Edit
Already many useful hints! Here some more imputs examples:
the street is 4.5 miles long
the budget was 430.000 dollars
Simple more clearer example for you
let regex = /\d+ (million|billion|millions|billions|trillion|trillions|meter|meters|mile|miles)/g
let match = "I have 3 billion dollars".match(regex)
let replace = match.map(x => x.split(" ").join("_"))
console.log(replace)
We can use str.replace with your original expression, if it would work:
const regex = /(\d+\.?(?:\d{1,2})?) (\bmillion\b|\bbillion\b|\bbillion\b|\bmillions\b|\bbillions\b|\btrillion\b|\btrillions\b|\bmeter\b|\bmeters\b|\bmile\b|\bmiles\b|\%)/gm;
const str = `3 billion
3 million`;
const subst = `<span class='highlighted'>" $1_$2 "</span>`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Also, we can slightly simplify our expression:
(\d+\.?(?:\d{1,2})?) (\bmillions?\b|\bbillions?\b|\btrillions?\b|\bmeters?\b|\bmiles?\b|\%)
const regex = /(\d+\.?(?:\d{1,2})?) (\bmillions?\b|\bbillions?\b|\btrillions?\b|\bmeters?\b|\bmiles?\b|\%)/gm;
const str = `3 billion
3 million
3 %
2 meters`;
const subst = `<span class='highlighted'>" $1_$2 "</span>`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
Demo
RegEx
If this expression wasn't desired and you wish to modify it, please visit this link at regex101.com.
RegEx Circuit
jex.im visualizes regular expressions:
match is not an array its a string. You could split it by ' ' join by _
var x = myFunction("I have 3 billion dollars");
function myFunction(text) {
return text.replace(/(\d+\.?(?:\d{1,2})?) (\bmillion\b|\bbillion\b|\bbillion\b|\bmillions\b|\bbillions\b|\btrillion\b|\btrillions\b|\bmeter\b|\bmeters\b|\bmile\b|\bmiles\b|\%)/gi, function (match) {
console.log(match)
return "<span class='highlighted'>" +match.split(' ').join('_')+ "</span>";
});
}
console.log(x)

JS : Remove all strings which are starting with specific character

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);

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];
}));

js code to remove space between numbers in a string

Is there any way to remove the spaces just numbers in a string?
var str = "The store is 5 6 7 8"
after processing the output should be like this:
"The store is 5678"
How to do this?
This is very close to santosh singh answer, but will not replace the space between is and 5.
const regex = /(\d)\s+(?=\d)/g;
const str = `The store is 5 6 7 8`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
https://regex101.com/r/nSZfQR/3/
You can try following code snippet.
const regex = /(?!\d) +(?=\d)/g;
const str = `The store is 5 6 7 8`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Hi You can try this.
var str = "The store is 5 6 7 8"
var regex = /(\d+)/g;
str.split(/[0-9]+/).join("") + str.match(regex).join('')
Hope this will work.
/([0-9]+) ([0-9]+)/ - removes space between digits.
But running s.replace replaces only first occurrences.
I put in into loop, so it keep deleting all spaces between two digits until there is no more spaces between digits.
prevS = '';
while(prevS !== s){
prevS = s; s = s.replace(/([0-9]+) ([0-9]+)/, '$1$2');
}

Categories

Resources