Help with regex in javascript - javascript

Whatever string is given I have to see if there is exactly one space after and before =, If it is more than one space in either side I have to reduce that to one and if there is none, I have to insert one.
How should I do that ? String can contain anything.
Thanks

You can do this:
str = str.replace(/ *= */g, " = ");
This will replace all = characters regardless of how many spaces it is surrounded by. The * quantifier will match as most spaces as possible while allowing even no spaces at all.

Try this:
var out = in.replace(/ *= */g, " = ");
Basically just replace zero or more instances of a space with a space and you get both desired results. If zero, then you get one. If more than one, you get one.

Make the following replacement:
s = s.replace(/ *= */g, ' = ')

myString.replace(/\s*=\s*/g, " = ")
will do the same as other given answers, but allow any type of space characters to be replaced (spaces, tabs, etc.).

Related

Checking if numbers are valid from inputs then adding them

Not sure there's a way to do this but what's happening is that I am adding 2 values from inputs then displaying them in a label $totalRetailAmountField. However, sometimes if you put dashes in either of the numbers, it's throwing off the final number (even when using a regex to strip out dashes, commas, etc). Is there a way to first check the numbers, then add them if they are? Thanks
function calcTotalRetailVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1.replace(/(,|[^\d.-]+)+/g, '')) + parseFloat(num2.replace(/(,|[^\d.-]+)+/g, ''));
if (!isNaN(result)) {
$totalRetailAmountField.text('$' + result.toFixed(2));
}
}
calcTotalRetailVal();
$oneTimeCostField.on("keydown keyup", function() {
calcTotalRetailVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcTotalRetailVal();
});
In your pattern (,|[^\d.-]+)+ you use an alternation to match either a comma, or a negated character class that match any character that is NOT listed due to using the ^ at the start like [^\d.-]
That means you are not removing digits, dots but you are also not removing dashes.
regex101 demo
Depending on what you want to replace with an empty string, you could use a single character class and list what you would like to replace like matching a comma, dash or whitespace char [,\s-], or use \D+ to match all non digits.
For example num1.replace(/[,\s-]+/g, '') or num1.replace(/\D+/g, '')
Not sure if I understood the question right but if your intent is to get rid of all possible dashes in a string, using the following regExp as the first parameter of your replace method should be fine I suppose.
/-/g
So your code would go from
var result = parseFloat(num1.replace(/(,|[^\d.-]+)+/g, '')) + parseFloat(num2.replace(/(,|[^\d.-]+)+/g, ''));
to
var result = parseFloat(num1.replace(/-/g, '')) + parseFloat(num2.replace(/-/g, ''));
In fact the regExp you're using does match anything that's not a digit, the . character or a dash.

Match parts of code

I'm trying to match parts of code with regex. How can I match var, a, =, 2 and ; from
"var a = 2;"
?
I believe you want this regexp: /\S+/g
To break it down: \S selects all non-whitespace characters, + makes sure you it selects multiple non whitespace characters together (i.e. 'var'),
and the 'g' flag makes sure it selects all of the occurrences in the string, and instead of stopping at the first one which is the default behavior.
This is a helpful link for playing around until you find the right regexp: https://regex101.com/#javascript
var str = "var a = 2;";
// clean the duplicate whitespaces
var no_duplicate_whitespace = str.replace(new RegExp("\\s+", "g"), " ");
// and split by space
var tokens = no_duplicate_whitespace.split(" ");
Or as #kuujinbo pointed out:
str.split(/\s+/);

How to replace all \n with space? [duplicate]

I have a var that contains a big list of words (millions) in this format:
var words = "
car
house
home
computer
go
went
";
I want to make a function that will replace the newline between each word with space.
So the results would something look like this:
car house home computer go went
You can use the .replace() function:
words = words.replace(/\n/g, " ");
Note that you need the g flag on the regular expression to get replace to replace all the newlines with a space rather than just the first one.
Also, note that you have to assign the result of the .replace() to a variable because it returns a new string. It does not modify the existing string. Strings in Javascript are immutable (they aren't directly modified) so any modification operation on a string like .slice(), .concat(), .replace(), etc... returns a new string.
let words = "a\nb\nc\nd\ne";
console.log("Before:");
console.log(words);
words = words.replace(/\n/g, " ");
console.log("After:");
console.log(words);
In case there are multiple line breaks (newline symbols) and if there can be both \r or \n, and you need to replace all subsequent linebreaks with one space, use
var new_words = words.replace(/[\r\n]+/g," ");
See regex demo
To match all Unicode line break characters and replace/remove them, add \x0B\x0C\u0085\u2028\u2029 to the above regex:
/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g
The /[\r\n\x0B\x0C\u0085\u2028\u2029]+/g means:
[ - start of a positive character class matching any single char defined inside it:
\r - (\x0D) - \n] - a carriage return (CR)
\n - (\x0A) - a line feed character (LF)
\x0B - a line tabulation (LT)
\x0C - form feed (FF)
\u0085 - next line (NEL)
\u2028 - line separator (LS)
\u2029 - paragraph separator (PS)
] - end of the character class
+ - a quantifier that makes the regex engine match the previous atom (the character class here) one or more times (consecutive linebreaks are matched)
/g - find and replace all occurrences in the provided string.
var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";
Code : (FIXED)
var new_words = words.replace(/\n/g," ");
Some simple solution would look like
words.replace(/(\n)/g," ");
No need for global regex, use replaceAll instead of replace
myString.replaceAll('\n', ' ')

Escape / in .split()

Need to escape / in javascript .split() function but cannot seem to figure out!
input -> string "07777/25555,00255" or any of 0777/2555 0777,2555
output -> array {07777,25555,00255}
var p = item.gdp.split(/ , | \//);
Not really good with regex!
What this does is split on either " , " or " /" (note the space characters: space comma space and space forward slash). Your regular expression is absolutely fine if that's what you're intending to replace on.
Here's a Regexper visualisation:
Update
There are no spaces in your string at all, so you need to remove those:
item.gdp.split(/,|\//);
With this, your result will be:
["07777", "25555", "00255"]
A more practical regular expression to use though would be /[,\/] - the square brackets will match on any character held within them.
var item={gdp:"07777/25555,00255"};
var p = item.gdp.split(/[,/]/);
document.write(p[0] + "<br>" + p[1] + "<br>" + p[2]);
07777
25555
00255
Here's one
split(/\s*[,\/]\s*|\s+/);
If you are splitting on only comma and slash as in your first string
"07777/25555,00255"
you can simply split on the character class containing those two characters [,/]
Within a character class the slash does not need to be escaped, so the resulting statement would be
var p = item.gdp.split(/[,/]/);
If you also want to split on space, as in your other example 0777/2555 0777,2555 simply add space to the character class:
var p = item.gdp.split(/[, /]/);
or to split on any whitespace (space, tab, etc.) use the predefined \s:
var p = item.gdp.split(/[,\s/]/);
Further, you can collapse multiple whitespace, but then you need to go beyond a simple character class. Compare...
var str="07777/25555,00255 0777,3444";
// split on white, comma, or slash. multiple spaces causes multiple results
str.split(/[\s,/]/)
// -> ["07777", "25555", "00255", "", "", "", "", "0777", "3444"]
// split on multiple whitespace, OR on comma or slash
str.split(/\s+|[,/]/)
// -> ["07777", "25555", "00255", "0777", "3444"]
input.split(/[\/\s,]+/)
Is this what you are looking for?

Javascript - How to remove all extra spacing between words

How can I remove all extra space between words in a string literal?
"some value"
Should become
"some value"
Also,
" This should become something else too . "
Becomes
"This should become something else too ."
Do not worry about moving the .. Just as above is fine. I know I can use $.trim(str) to achieve the trailing/ending space removal. But, I'm not sure how to do the 1 space between words trick.
var string = " This should become something else too . ";
string = string.replace(/\s+/g, " ");
This code replaces a consecutive set of whitespace characters (\s+) by a single white space. Note that a white-space character also includes tab and newlines. Replace \s by a space if you only want to replace spaces.
If you also want to remove the whitespace at the beginning and end, include:
string = string.replace(/^\s+|\s+$/g, "");
This line removes all white-space characters at the beginning (^) and end ($). The g at the end of the RegExp means: global, ie match and replace all occurences.
var str = " This should become something else too . ";
str = str.replace(/ +(?= )/g,'');
Here's a working fiddle.
In case we want to avoid the replace function with regex,
We can achieve same result by
str.split(' ').filter(s => s).join(' ')
// var str = " This should become something else too . ";
// result is "This should become something else too ."
First, split the original string with space, then we will have empty string and words in an array. Second, filter to remain only words, then join all words with a whitespace.
var str = " This should become something else too . "
$.trim(str).replace(/\s(?=\s)/g,'')
This uses lookahead to replace multiple spaces with a single space.
jsFiddle Example
" This should become something else too . ".replace(/[\s\t]+/g,' ');
Another (perhaps easier to understand) regexp replacement that will do the trick:
var input = /* whatever */;
input = input.replace(/ +/g, ' ');
The regexp matches one or more spaces, so the .replace() call replaces every single or repeated space with a single space.
var str = 'some value';
str.replace(/\s\s+/g, ' ');

Categories

Resources