How do I replace all string values in this JavaScript statement? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
replace all occurrences in a string
I have this string:
"12-3-02"
And I would like to convert it to :
"12/3/02"
How would I do this? I 've tried :
.replace(/-/,"/")
But this only replaces the first one it finds. How do I replace all instances?

One of these (using split, or a global RegEx flag):
str = str.split('-').join('/'); // No RegExp needed
str = str.replace(/-/g, '/'); // `g` (global) has to be added.

Add the g (global) modifier to the regex, to match all -s.
.replace(/-/g,"/")

If you want to replace all the occurences of - by / then use this where g specifies the global modifier.
"12-3-02".replace(/-/g,"/");
Working demo - http://jsfiddle.net/ShankarSangoli/QvbM8/

Try with:
"12-3-02".replace(/-/g, '/');

This question has been posed about a thousand times, but no one has ever considered the possibility that, in the real world, characters can occur in places where you might not expect.(Typo's in input or replacing parts of words when you only wanted to replace a single word...
var reformat = '01-11-2012'.replace(/(([0-9]+)(?=\-))\-(?=[0-9])/g,'$1/');
This will only replace '-' characters that are preceded and followed by a number.

Related

Regex non-greedy and global modifiers not working as expected with JavaScript .match [duplicate]

This question already has answers here:
Javascript regular expressions modifier U [duplicate]
(3 answers)
Closed 5 months ago.
I'm trying to create a Regex that will return text that is wrapped by parentheses. For example, in the following string combination:
const regexString = "asdf (asdfasd asdfas) asdfasd asdfasd asdf(asfda) asdfasd (asdfasd)"
the regex should return only: (asdfasd asdfas), (asfda), and (asdfasd) as individual capture groups.
Using regex101.com I was able to put this combination together:
/(\(.+\))/gU
This regex combo works, but when I try to implement this in Javascript .match or even with .exec, I am simply returned the entire string.
For example,
regexString.match(/(\(.+\).*?)/g)
returns the entire string.
I believe the issue has to do my use of the ungreedy .*? modifier and the global /g modifier. Both of these are used in the working example from regex101.com, but I haven't been able to determine exactly why these modifiers or possibly the regex are not functioning the same when I try to use them in Javascript directly.
Thank you for any insight!
I believe you dont get entire string, but by using greedy modifier you get all characters between first opening and last closing parentheses. In your example the returned value is array with single string:
['(asdfasd asdfas) asdfasd asdfasd asdf(asfda) asdfasd (asdfasd)']
You need to change your regex with nongreedy ? to get least possible amount of characters between parentheses
regexString.match(/(\(.+?\).*?)/g)
Then the returned result will be:
['(asdfasd asdfas)', '(asfda)', '(asdfasd)']
what you're searching for is /\([^)]*\)/g
\( : will match the opening parenthese
[^)] : will match any non closing parenthese
* : will match many times the last character
\) : will match a closing parenthese

How can I replace every regex match with itself and some concatenations? [duplicate]

This question already has answers here:
Using $0 to refer to entire match in Javascript's String.replace
(2 answers)
Closed 3 years ago.
I have a console output that is a string {x:0,y:0,width:1920,height:1080} and need to convert it to object but I can't JSON.parse() it until all properties are surounded by quotes.
I managed to find this regex expression that will match with any word: \b[\w]+\b but I don't know how to use every match to replace '"' + match + '"' on both sides. I realized there are also numbers in there so maybe this would be a better regex: \b[a-zA-Z]+\b provided that property names never include numbers.
Use a group (i.e.: enclose the pattern with ( and )) and access it with $1:
var out = "{x:0,y:0,WIDTH:1920,hEiGhT:1080}";
var rgx = /\b([a-z]+)\b/gi; // use the flag 'i' to make it case-insensitive
console.log(out.replace(rgx, '"$1"'));

Regex allows spaces [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 5 years ago.
For the following regex expression:
var regex = new RegExp("^(www\\.)?[0-9A-Za-z-\\.#:%_\+~#=]+(\\.[a-zA-Z]{2,})+(/.*)?(\\?.*)?");
I don't understand why the string "www.goo gle.com" passes the regex test. When I did this:
var regex = new RegExp("^(www\\.)?[0-9A-Za-z-\\.#:%_\+~#=]+(\\.[a-zA-Z]{2,})+(/.*)?(\\?.*)?$");
i.e. adding $ in the end of the regex string prevents the above string passing, which is what I would want.
I tried finding a "simulator" online to help me figure out how the regex is matching but couldn't find much help.
www.goo gle.com passes the test since, www. is matched by [0-9A-Za-z-\\.#:%_\+~#=]+ and
goo is matched by (\.[a-zA-Z]{2,})+. In contrast, (www\\.)?, and the last two groups are optional, so the regex is satisfied even if they are not matched, hence there's no need to further match gle.com.
By adding $, the regex no longer matches, since the space is not matched by any of the subexpressions.

Regular expression seems to treat one string as multiple substrings [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 7 years ago.
Why the following code returns "ZZZCamelCase"?? Doesn't such regex examine if the string starts and ends with small case a-z? As what I understand, the str variable should match such condition, so the console output should be "ZZZZZZZZZZZZ", but obviously it somehow breaks the str, and examine the substring against the regex. Why? and how can I tell the program to treat "testCamelCase" as one string?
var str = "testCamelCase";
console.log(str.replace(/^[a-z]+/, 'Z')); // ZZZCamelCase
Here you are matching one or more lower case letters. That's going to be 'test' in your string, because after that comes an uppercase 'C'. So only 'test' gets rpelaced by 'ZZZ'
console.log(str.replace(/^[a-z]+/, 'ZZZ')); // ZZZCamelCase
Use
str.replace(/[a-z]/ig, 'Z')
to get 'ZZZZZZZZZZZZ'
You are forgetting, that regex is case sensitive. This means, that [a-z] doesn't capture the whole string. [a-zA-Z] does. So does [\w] including digits from 0-9.

Replace pattern within string with space [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 7 years ago.
I am getting long string with multiple occurances of pattern './.'. The string has dates as well in a format of dd.mm.yyyy.
First I tried with javascript replace method as:
str.replace('./.', ''). But it replaced only first occurance of './.'
Then I tried another regex which replaces special characters but it didn't work as it replaced '.' within dates as well.
How do I replace multiple occurances of a pattern './.' without affecting any other characters of a string ?
. is a special character in a regexp, it matches any character, you have to escape it.
str.replace(/\.\/\./g, '');
Use this simple pattern:
/\.\/\./g
to find all "./." strings in your text.
Try it :
str.replace(/\.\/\./g, '');
Escape . and d \
Add a g for global
Like this
str = str.replace(/\./\./g, '');

Categories