Replacement by matching in Javascript - 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)

Related

Javascript regex replace string on string

This regex removes all after match the pattern and i need to remove only the match pattern and the value.
pattern = /(?<=ANO=).*/
obj.where_str = " AND EMPRESA='CMIP' AND ANO='2019' AND MES='1' AND RHID='4207' AND TO_CHAR(DT_ADMISSAO,'YYYY-MM-DD')='2001-08-01' AND ESTADO='A'"
obj.where_str = obj.where_str.replace(pattern, "'" + fieldValue + "'");
Thanks in advance
Method 1
My guess is that maybe you're trying to write an expression similar to:
\bANO='([^']*)'
The desired value to replace is in the capturing group:
([^']*)
RegEx Demo
const regex = /\bANO='([^']*)'/gm;
const str = ` AND EMPRESA='CMIP' AND ANO='2019' AND MES='1' AND RHID='4207' AND TO_CHAR(DT_ADMISSAO,'YYYY-MM-DD')='2001-08-01' AND ESTADO='A'`;
const subst = `ANO='Another_value_goes_here'`;
const result = str.replace(regex, subst);
console.log(result);
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
And your code would probably look like:
const regex = /\bANO='([^']*)'/g;
const str = ` AND EMPRESA='CMIP' AND ANO='2019' AND MES='1' AND RHID='4207' AND TO_CHAR(DT_ADMISSAO,'YYYY-MM-DD')='2001-08-01' AND ESTADO='A'`;
const fieldValue = 2020;
const subst = 'ANO=\''.concat(fieldValue, "'");
const result = str.replace(regex, subst);
console.log(result);
Method 2
Another option would likely be:
(?<=\bANO=')\d{4}
which I guess/assume that there would no problem with a positive lookbehind.
RegEx Demo 2
const regex = /(?<=\bANO=')\d{4}/g;
const str = ` AND EMPRESA='CMIP' AND ANO='2019' AND MES='1' AND RHID='4207' AND TO_CHAR(DT_ADMISSAO,'YYYY-MM-DD')='2001-08-01' AND ESTADO='A'`;
const fieldValue = 2020;
const result = str.replace(regex, fieldValue);
console.log(result);

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 search strings with brackets using Regular expressions

I have a case wherein I want to search for all Hello (World) in an array. Hello (World) is coming from a variable and can change. I want to achieve this using RegExp and not indexOf or includes methods.
testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)']
My match should return index 1 & 2 as answers.
Use the RegExp constructor after escaping the string (algorithm from this answer), and use some array methods:
const testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)'];
const string = "Hello (World)".replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const regex = new RegExp(string, "i");
const indexes = testArray.map((e, i) => e.match(regex) == null ? null : i).filter(e => e != null);
console.log(indexes);
This expression might help you to do so:
(\w+)\s\((\w+)
You may not need to bound it from left and right, since your input strings are well structured. You might just focus on your desired capturing groups, which I have assumed, each one is a single word, which you can simply modify that.
With a simple string replace you can match and capture both of them.
RegEx Descriptive Graph
This graph shows how the expression would work and you can visualize other expressions in this link:
Performance Test
This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.
repeat = 1000000;
start = Date.now();
for (var i = repeat; i >= 0; i--) {
var string = "Hello (World";
var regex = /(\w+)\s\((\w+)/g;
var match = string.replace(regex, "$1 & $2");
}
end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");
testArray = ['Hello (World', 'Hello (World)', 'hello (worlD)'];
let indexes = [];
testArray.map((word,i)=>{
if(word.match(/\(.*\)/)){
indexes.push(i);
}
});
console.log(indexes);

Regex with or without quotes and one or more separated by commas

I need to get the values inside a string from an input form to use in a search, i will some examples:
Example 1: name="Peter Nash","Costa", should return Peter Nash and Costa.
Example 2: name='Peter Nash',"Costa", should return: Peter Nash and Costa.
Example 3: name="Peter Nash", should return: Peter Nash.
Example 4: name=Peter,"Costa", should return: Peter and Costa.
Example 5: name=Peter,Costa, should return: Peter and Costa.
Example 6: name=Peter, should return: Peter.
The name is a variable, it can change.
Right now i'm using something like new RegExp(string_var + "\:([^ ]+)", "").exec(input);, but doesn't work with quotes or commas.
At its core, your sample text is comma-separated with optional quotes and can be treated like that. Thus, a .split regex is the right hammer for this problem. The only exception from a regular format is your variable-name prefix. The following split pattern does the heavy-lifting:
name=|,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)
Since you do not want to have the var name in the output, I am going to .filter it out. Also, quotes are removed using .replace on each element via .map.
Code Sample: Finally, everything wrapped up in a nice function:
function splitString(stringToSplit, separator) {
var arr = stringToSplit.split(separator)
.map(str => str.replace(/^["']|["']$/g, ``)) //remove surrounding quotes
.filter(Boolean); //filter zero length results
console.log('The array has ' + arr.length + ' elements: ' + arr.join(' and '));
}
const comma = /name=|,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/gm;
splitString(`name="Peter Nash","Costa"`, comma);
splitString(`name='Peter Nash',"Costa"`, comma);
splitString(`name="Peter Nash"`, comma);
splitString(`name=Peter,"Costa"`, comma);
splitString(`name=Peter,Costa`, comma);
splitString(`name=Peter`, comma);
The regex:
(?!^name=)("|')?(?<first_name>([A-z]|\s)*)("|')*(\,{0,1})("|')*(?<second_name>(([A-z]|\s)*))("|')*$
https://regex101.com/r/3gKo9M/1
Code Sample:
let s = [
"name=\"Peter Nash\",\"Costa\"",
"name=\"Peter Nash\",\"Costa\"",
"name='Peter Nash',\"Costa\"",
"name=\"Peter Nash\"",
"name=Peter,\"Costa\"",
"name=Peter,Costa",
"name=Peter",
];
const regex = /(?!^name=)("|')?(?<first_name>([A-z]|\s)*)("|')*(\,{0,1})("|')*(?<second_name>(([A-z]|\s)*))("|')*$/;
s.forEach(function(input){
let regexResult = regex.exec(input);
let output = regexResult["groups"]["first_name"];
if(regexResult["groups"]["second_name"]!=""){
output += ' AND ' + regexResult["groups"]["second_name"];
}
console.log(output);
});
What you also might do is to split the string by name= and take the second part which will be a comma separated list. Then you could use a regex to capture 3 groups and use a backreference in the third group (\1) to make sure that the starting quote has the same closing quote.
Then use replace with the second group \$2
let pattern = /^(["'])(.*)(\1)$/;
If you would also allow "Costa' you could leave out the backreference and replace the pattern with:
let pattern = /^(["'])(.*)(['"])$/;
let pattern = /^(["'])(.*)(\1)$/;
const strings = [
"name=\"Peter Nash\",\"Costa\"",
"name=\"Peter Nash\",\"Costa\"",
"name='Peter Nash',\"Costa\"",
"name=\"Peter Nash\"",
"name=Peter,\"Costa\"",
"name=Peter,Costa",
"name=Peter",
"test",
"test,",
"name= ",
"name=\"Peter' test \" Nash\",\"Costa\"",
"name='Peter Nash\",\"Costa'"
];
strings.forEach((str) => {
let spl = str.split("name=");
if (spl.length === 2 && spl[1].trim() !== "") {
let result = spl[1].split(",").map(s => s.replace(pattern, "$2"));
console.log(str + " ==> " + result.join(" and "));
}
});

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