Javascript regex replace string on string - javascript

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

Related

How to replace string using regex in javascript?

How to check a string and replace the space into "_" ?
let str = "hello #%123abc456:nokibul amin mezba jomadder% #%123abc456:nokibul% #%123abc456:nokibul amin mezba%"
str = str.replace(regex, 'something');
console.log(str);
// Output: str = "hello #%123abc456:nokibul_amin_mezba_jomadder% #%123abc456:nokibul% #%123abc456:nokibul_amin_mezba%"
Please help me out :)
Check this out. I think it's gonna help
Hints:
/:(\w+\s*)+/g Separates the :nokibul amin mezba jomadder as a group.
Replace the group with index-wise templating {0}, {1} ... {n}.
Mapping the groups. Ex: :nokibul amin mezba jomadder to :nokibul_amin_mezba_jomadder.
Finally, replacing the templates {index} with groups.
let str = "hello #%123abc456:nokibul amin mezba jomadder% #%123abc456:nokibul% #%123abc456:nokibul amin mezba%";
/* Extracting Groups */
let groups = str.match(/:(\w+\s*)+/g);
/* Formatting Groups: Replacing Whitespaces with _ */
let userTags = groups.map((tag, index) => {
/* Index wise string templating */
str = str.replace(tag, `{${index}}`)
return tag.replace(/\s+/g, "_");
});
console.log(str);
console.log(userTags);
/* Replacing string templates with group values */
userTags.forEach((tag, index) => str = str.replace(`{${index}}`, tag));
console.log(str);
Hint: You can use https://regex101.com/ to test whether a regex works, it supports substitution as well.
Regex being used: (\w+)[ ], to grep all words between space, and use $1_ to substitute the space to underscore.
const regex = /(\w+)[ ]/gm;
const str = `Input: str="nokibul" output: str="nokibul"
Input: str="nokibul amin" Output: str="nokibul_amin"
Input: str="nokibul amin mezba" Output: str="nokibul_amin_mezba"
Input: str="nokibul amin mezba jomadder" Output: str="nokibul_amin_mezba_jomadder"`;
const subst = `$1_`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Simple one liner
str.replace(/:[^%]*%/g, arg => arg.replace(/ /g, '_'))
Explanation:
/:[^%]*%/g Find all occurrences starting with : and ending at %
This will return patterns like this :nokibul amin mezba jomadder% :nokibul% :nokibul amin mezba%
Next is to replace all space characters with underscores using this replace(/ /g, '_')

RegEx to return only matching group using only replace method

Is there a way to return only the matching group using only replace?
I have this string,
"xml version 2.1.2-emerald https://www.example.com"
and I want to pull the version out of it.
I'm using this RegEx:
const regex = /\sversion\s(.*?)\s/;
const str = `xml version 2.1.2-emerald https://www.example.com`;
const subst = `$1`;
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
// desired result: "2.1.2-emerald"
Except I want the result to contain only the match. Is there a way to do this with the replace() method?
Yes, the key is to fully collect the entire string data, then replace it with the desired group:
const regex = /.*\sversion\s(.*?)\s.*/gs;
const str = `xml version 2.1.2-emerald https://www.example.com`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Instead of replace, match instead, and extract the first captured group. You can also use (\S+) instead of (.*?)\s:
const regex = /\sversion\s(\S+)/;
const str = `xml version 2.1.2-emerald https://www.example.com`;
const result = str.match(regex);
console.log(result[1]);
If there may not be a match, check that the result isn't null first:
const regex = /\sversion\s(.*?)\s/;
const str = `foo bar`;
const result = str.match(regex);
if (result) {
console.log(result[1]);
}
If you want the full match to be just what you're looking for, you can use lookbehind, though this will only work on newer browsers, and is not a good cross-browser solution:
const regex = /(?<=\sversion\s)\S+/;
const str = `xml version 2.1.2-emerald https://www.example.com`;
const result = str.match(regex);
console.log(result[0]);

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)

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 replace a string using regexp in JavaScript

I want to filter a given string and replace some common words from a given string:
const str ='api/knwl/tests/products';
const str1 = 'api/users';
const str2 = 'api/tests/providers';
I want to filter the words 'api', 'knwl' or 'tests' from a given strings.
I tried somthing with regexp:
/(?!(tests|api|knwl))/g
But it doesn't work. How can I fix this issue? I'm not expert on regexp.
Regex - /(tests|api|knwl)/g;
const str ='api/knwl/tests/products';
const str1 = 'api/users';
const str2 = 'api/tests/providers';
const filterRegex = str.replace(/(tests|api|knwl)/g,''); // replace all occurence of strings (tests,api,knwl) to empty.

Categories

Resources