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');
}
Related
The below two strings have different apostrophes. I am pretty stumped on how to convert them so that they are the same style (both are either slanted or both are either straight up and down). I have tried everything from enclosing it in `${}`` to regex expressions to remove and replace. I am not sure how it is being stored like this but when I try to search for string1 inside of string2 it doesn't recognize the index because (I believe) of the mismatch apostrophe. Has anyone run into this before?
//let textData = Father’s
//let itemData = Father's Day
const newData = currData.filter(item => {
let itemData = `${item.activityName.toUpperCase()}`;
let textData = `${text.toUpperCase()}`; //coming in slanted
let newItemData = itemData.replace(/"/g, "'");
let newTextData = textData.replace(/"/g, "'");
return newItemData.indexOf(newTextData) > -1;
});
first of all, your code won't run because you are not wrapping your string variables with ", ' or `, depending on the case.
if your string has ' you can use " or ` like this:
"Hello, I'm a dev"
or
"Hello, I`m a dev"
but you can not mix them if you have the same symbol, so this is not allowed:
'Hello, I`m a dev'
here you have a working example of your strings wrapped correctly and also replacing the values to match the strings.
note: please look that the index in this case is 0 because the whole string that we are looking matches from the 0 index to the length of the response1.
also I added a case if you want to get the partial string from string2 based on the match of string1
let string1 = "FATHER’S"
let string2 = "FATHER'S DAY: FOR THE FIXER"
const regex = /’|'/;
const replacer = "'";
let response1 = string1.replace(regex, replacer);
let response2 = string2.replace(regex, replacer);
console.log(response1);
console.log(response2);
console.log("this is your index --> ", response2.indexOf(response1));
console.log("string 2 without string 1 -->", response2.slice(response2.indexOf(response1) + response1.length, response2.length))
You could do a search using a regex, allowing for whatever apostrophe variations you expect:
let string1 = "FATHER’S"
let string2 = "FATHER'S DAY: FOR THE FIXER"
const regex = string1.split(/['’"`]/).join("['’\"`]")
//console.log(regex);
const r = new RegExp(regex)
console.log(string2.search(r)); //comes back as 0
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);
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]);
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)
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