Regexp in Javascript: replace minus with comma+minus when condition is met - javascript

I need to replace \- minus with \,+- comma+minus when space/no-space/comma before the minus. In a SVG path I found this:
`201.86-38.778`
and I need to make it
`201.86,-38.778`.
I tried str.replace(/-/g,'\,-') but this creates additional commas when not needed.
Update, I also need this to work like this:
`201.86 -38.778` // notice the space
to make it
`201.86,-38.778`.

You can use
/(^|[^,\s])-/g
See the regex demo
Breakdown:
(^|[^,\s]) - match and capture the start of string or a character other than a comma or whitespace (that will be referenced to with the $1 backreference in the replacement pattern)
- - a literal hyphen.
In the replacement pattern, use $1,-, a backreference to the captured text + comma and a hyphen.
Demo:
var re = /(^|[^,\s])-/g;
var str = '201.86-38.778';
var result = str.replace(re, '$1,-');
document.body.innerHTML = result;

Find with ([-+]) and replace with ,\1. Regex101 Demo

Related

js regex to wrap numbers and variables in string in span tags

i have a string like so:
${1}${2}${3}${4}%9${5}00
And I'm wanting to wrap all the numbers and vars in span tags But the issue is there can be an unlimited number of "${1}" variables in this string.
The current regex I'm using is
str.replace(/([0-9\/\+\(\)\%\-\*v]{1})/g, '<span>$1</span>')
But the problem with this regex is it wraps the $, { and } in a separate span tag. I'm wanting to wrap the "${1}" in its own span tag.
How would I do this and if possible can you explain the regex.
Thanks
Working example:
et str = '${1}${2}${3}${4}%9${5}00';
let copy = str.replace(/(\$\{\d+\}|[\d/+()%*v-])/g, '<span>$1</span>');
console.log('Copy: ', copy)
IIRC,
How about a simple regex with
str.replace(/(\$\{\d\})/g, '<span>$1</span>')
The output is:
'<span>${1}</span><span>${2}</span><span>${3}</span><span>${4}</span>%9<span>${5}</span>00'
It matches ${<digit>}, if you want to match more digits, for examples ${11} or ${123}, you can simply put \d+ in place of \d.
Here is the updated version matching the special characters as well with different capture groups.
const str = "${1}${2}${3}${4}%9${5}00"
const out = str.replace(/(\$\{\d+\}|\%|\d)/g, '<span>$1</span>')
console.log(out)
let str = '${1}${2}${3}${4}%9${5}00';
str = str.replace(/\$\{\d+\}|[\d/+()%*v-]/g, '<span>$&</span>');
console.log(str);
The regex will match either of two alternatives separated by |.
First, it will try to match a "variable" using \${\d+} then it will try to match a number or symbol using [\d\/+()%*v-].
Whatever is matched is then referenced using $& (the full match) in the replacement string.

Regex: match last and second-last character

I need to wrap the two last characters in a string in a separate <span>:
-1:23 // This is what I have
-1:<span>2</span><span>3</span> // This is what I want
The following matches the last character – but how can I make it match the second last as well?
str.replace(/(.$)/, "<span>$1</span>");
Thanks :)
You may use
.replace(/.(?=.?$)/g, "<span>$&</span>")
See the regex demo
If these must be digits, replace . with \d:
.replace(/\d(?=\d?$)/g, "<span>$&</span>")
The pattern matches
\d - a digit
(?=\d?$) - that is followed with an end of string or a digit and end of string.
The $& is a replacement backreference that references the whole match value from the string replacement pattern.
JS demo:
console.log("-1:23".replace(/.(?=.?$)/g, "<span>$&</span>"));
console.log("-1:23".replace(/\d(?=\d?$)/g, "<span>$&</span>"));
Now, to make it more dynamic, you may use a limiting (range/interval) quantifier:
function wrap_chars(text, num_chars) {
var reg = new RegExp(".(?=.{0," + (num_chars-1) + "}$)", "g");
return text.replace(reg, "<span>$&</span>");
}
console.log(wrap_chars("-1:23", 1)); // wrap one char at the end with span
console.log(wrap_chars("-1:23", 2)); // wrap two chars at the end with span
You can add another group before the last one, which also matches a single character ((.)), then wrap each of them using references ($1 and $2):
var str = '-1:23'.replace(/(.)(.)$/, '<span>$1</span><span>$2</span>')
console.log(str);

regex replace only a part of the match

I want to replace only a part of the string of a regex pattern match. I found this answer but I don't get it...
How do I use substitution?
Example of what I want: keep the first slug digit, only replace others
/09/small_image/09x/ > /09/thumbnail/
1st: unknown digit
2nd: "small_image"
3rd: unknown digit + "x"
Here is what I have so far:
var regexPattern = /\/\d\/small\_image\/\d*x/;
var regexPattern = /\/\d\/(small\_image\/\d*x)$1/; ??
var result = regexPattern.test(str);
if (result) {
str = str.replace(regexPattern, 'thumbnail');
}
var input = "/09/small_image/09x/";
var output = input.replace(/(\/\d+\/)small_image\/\d*x/, "$1thumbnail");
console.log(output);
Explanation:
Put the part you want to keep in parentheses, then refer to that as $1 in the replacement string - don't put $1 in your regex. So (\/\d+\/) means to match a forward slash followed by one or more digits, followed by another forward slash.
(Note that you don't need to escape underscores in a regex.)
Go with
var regexPattern = /(\/\d+\/)small\_image\/\d*x/;
and
str = str.replace(regexPattern, '$1thumbnail');
First, you were missing the +. Because 09 are two digits, you need the regexp to match one or more digits (\ḑ would be exactly one). This is accomplished by \d+
Second, everything you match is being removed at first. To get the /09/ part back afterwards, you have to remember it by putting it into brackets in the regexp (...) and afterwards reference it in the replacement via $1
One could as well create other groups and reference them by $2,$3 ...

JS String: Add whitespace between numbers and letters

i need a regular expression or any other method to add whitespaces between numbers and letters in a string.
Example:
"E2356" => "E 2356"
"E123-F456" => "E 123-F 456"
I already found a regular expression capable of it but it is not possible with Javascript:
(?<=[^0-9])(?=[0-9])
Thanks!
Instead of a look-behind, just match the non-digit:
[^0-9](?=[0-9])
And replace with "$& ".
The [^0-9] subpattern will match 1 character that is not a digit that can be referenced with $& (the whole matched text) in the replacement pattern. (?=[0-9]) lookahead will make sure there is a digit right after it.
See demo
var re = /[^0-9](?=[0-9])/g;
var str = 'E2356<br/>E123-F456';
var result = str.replace(re, '$& ');
document.write(result);
Match the two-character sequence of letter followed by number, with capture groups for both the letter and number, then use String#replace with the $1 and $2 placeholders to refer to the content of the capture groups, with a space in between.
str.replace(/([^0-9])([0-9])/g, '$1 $2')
^^$1^^ ^^$2^
The g flag ensures all occurrences are replaced, of course.
Use String#replace:
'E123-F456'.replace(/([A-Z])(\d)/g, '$1 $2')
// >>> "E 123-F 456"
$1 and $2 are the captured groups from the regex and are separated by a space. The expression assumes you only have uppercase characters. Remember to add the g flag to your expression to replace every occurrence.
You cannot format a string using regex.
Regex helps you validate that whether a certain string follow the language described by expression.
Regex helps you capture certain parts of the string in different variables and then format them as you want to get the desired output.
So I would suggest you do something like this :
var data = "E2304" ;
var regex = ([^0-9])([0-9]*)/g ;
data.replace(/regex, '$1 $2') ;
Try below code
var test = "E123-F456".match(/[a-zA-Z]+|[0-9]+/g);
console.log(test.join(' '));
fiddle http://jsfiddle.net/anandgh/h2g8cnha/

Javascript reg exp not right

Here is a string str = '.js("aaa").js("bbb").js("ccc")', I want to write a regular expression to return an Array like this:
[aaa, bbb, ccc];
My regular expression is:
var jsReg = /.js\(['"](.*)['"]\)/g;
var jsAssets = [];
var js;
while ((js = jsReg.exec(find)) !== null) {
jsAssets.push(js[1]);
}
But the jsAssets result is
[""aaa").js("bbb").js("ccc""]
What's wrong with this regular expression?
Use the lazy version of .*:
/\.js\(['"](.*?)['"]\)/g
^
And it would be better if you escape the first dot.
This will match the least number of characters until the next quote.
jsfiddle demo
If you want to allow escaped quotes, use something like this:
/\.js\(['"]((?:\\['"]|[^"])+)['"]\)/g
regex101 demo
I believe it can be done in one-liner with replace and match method calls:
var str = '.js("aaa").js("bbb").js("ccc")';
str.replace(/[^(]*\("([^"]*)"\)[^(]*/g, '$1,').match(/[^,]+/g);
//=> ["aaa", "bbb", "ccc"]
The problem is that you are using .*. That will match any character. You'll have to be a bit more specific with what you are trying to capture.
If it will only ever be word characters you could use \w which matches any word character. This includes [a-zA-Z0-9_]: uppercase, lowercase, numbers and an underscore.
So your regex would look something like this :
var jsReg = /js\(['"](\w*)['"]\)/g;
In
/.js\(['"](.*)['"]\)/g
matches as much as possible, and does not capture group 1, so it matches
"aaa").js("bbb").js("ccc"
but given your example input.
Try
/\.js\(('(?:[^\\']|\\.)*'|"(?:[\\"]|\\.)*"))\)/
To break this down,
\. matches a literal dot
\.js\( matches the literal string ".js("
( starts to capture the string.
[^\\']|\\. matches a character other than quote or backslash or an escaped non-line terminator.
(?:[\\']|\\.)* matches the body of a string
'(?:[\\']|\\.)*' matches a single quoted string
(...|...) captures a single quoted or double quoted string
)\) closes the capturing group and matches a literal close parenthesis
The second major problem is your loop.
You're doing a global match repeatedly which makes no sense.
Get rid of the g modifier, and then things should work better.
Try this one - http://jsfiddle.net/UDYAq/
var str = new String('.js("aaa").js("bbb").js("ccc")');
var regex = /\.js\(\"(.*?)\"\){1,}/gi;
var result = [];
result = str.match (regex);
for (i in result) {
result[i] = result[i].match(/\"(.*?)\"/i)[1];
}
console.log (result);
To be sure that matched characters are surrounded by the same quotes:
/\.js\((['"])(.*?)\1\)/g

Categories