Why cant i replace another - with /? [duplicate] - javascript

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
JavaScript .replace only replaces first Match [duplicate]
(7 answers)
Closed 1 year ago.
Write a function normalize, that replaces '-' with '/' in a date string.
Example: normalize('20-05-2017') should return '20/05/2017'.
This is what I wrote:
function normalize(str) {
let replaced = str.replace('-', '/')
return replaced
}
I can't replace the other - with / can someone explain how to do this?

When you use replace, only the first instance is replaced. See replace
What you can do is either
Use replaceAll
const replaced = str.replaceAll('-', '/');
Or
const replaced = str.replace(/-/g, '/');
The g means Global, and causes the replace call to replace all matches, not just the first one

Instead of str.replace('-','/') use str.replaceAll('-','/')

Related

How to replace few characters in string, if we know the prefix of the characters we want to replace in javascript [duplicate]

This question already has an answer here:
javascript replace query string value [duplicate]
(1 answer)
Closed 2 years ago.
I want to replace few characters if we already know the prefix of those character. Ex:
If my string is
limit=100&launch_year=2016&
and i want to replace it with
limit=100&launch_year=2017&
But the string is dynamic and we only know launch_year, so is it possible to find 2016 and replace it with 2017 if i only know that there is launch_year in the dynamic string.
String replace with regex /(.*limit=100&launch_year=)\d{4}(.*)/.
Capture the prefix and suffix around the year value you want to replace and rebuild the string with new year.
const data = "limit=100&launch_year=2016&";
const regex = /(.*launch_year=)\d{4}(.*)/;
const replaceYear = (data, year) => data.replace(regex, `$1${year}$2`);
console.log(replaceYear(data, "2017"));
console.log(replaceYear(data, "2020"));
It seems like your input is a query string so I would suggest to use parser and then change it...
const queryParams = new URLSearchParams('limit=100&launch_year=2016');
queryParams.set('launch_year','2017');
console.log(queryParams.toString() + '&' );
// "limit=100&launch_year=2017&"

Replacing "/" with ":" using jQuery [duplicate]

This question already has answers here:
Fastest method to replace all instances of a character in a string [duplicate]
(14 answers)
Closed 6 years ago.
New to jQuery & JavaScript.
I have
var x = location.pathname;
(ex: /abc/collection/tea/green/index.php)
Like this I have various pathname retrieved using location.pathname.
I want to replace all "/" in the pathname with ":" (I mean a / with a :) and also I don't want the .php which is at the end. Any help please.
This has nothing to do with jQuery. You can use JavaScript to replace your string.
Like this:
var x = location.pathname;
x = x.replace(/\//g, ":");
or just
var x = location.pathname.replace(/\//g, ":");
You can also use the same method to remove the ".php" by adding this:
x = x.replace(/\.php$/i, "");
(assuming you only need to replace it once at the end)
Basically you have to use the regex version of str.replace() and the g (global) switch to do a replace all. Use the str.replace(/texthere/g, "replacement") pattern to replace more than one occurrence - just remember to properly escape 'texthere' so characters don't conflict.

Replace substring with edited substring [duplicate]

This question already has answers here:
Why isn't this split in javascript working?
(2 answers)
Closed 8 years ago.
please, could you help me with my task: I need to replace part of string and probably the best way is regular expression but I don't know, how to make it working. I want to do this:
http://someweb.com/section/&limit=10&page=2
replace page=2 with page=3 so string will be:
http://someweb.com/section/&limit=10&page=3
I tried to do something like this:
// set string in t variable
t.replace('/page=[0-9]/', 'page=$1++') });
Thank you very much for your help :)
In our case first argument should be regexp, but in your variant this is string '/page=[0-9]/' (remove '). In replace you can pass function as second argument, and do with matched data what you want. (for example add +1 to page=)
var str = "http://someweb.com/section/&limit=10&page=2";
str.replace(/page=(\d+)/, function (match, page) {
return 'page=' + (+page + 1); // plus before page converts string to number
});
Example
You can also try below code.
var url = "http://someweb.com/section/&limit=10&page=2",
reExp = /page=([0-9])+/,
result = reExp.exec(url);
url = url.replace(reExp, 'page=' + (+result[1] + 1));
console.log(url)

JS replacing all occurrences of string using variable [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 9 years ago.
I know that str.replace(/x/g, "y")replaces all x's in the string but I want to do this
function name(str,replaceWhat,replaceTo){
str.replace(/replaceWhat/g,replaceTo);
}
How can i use a variable in the first argument?
The RegExp constructor takes a string and creates a regular expression out of it.
function name(str,replaceWhat,replaceTo){
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
If replaceWhat might contain characters that are special in regular expressions, you can do:
function name(str,replaceWhat,replaceTo){
replaceWhat = replaceWhat.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp(replaceWhat, 'g');
return str.replace(re,replaceTo);
}
See Is there a RegExp.escape function in Javascript?
The third parameter of flags below was removed from browsers a few years ago and this answer is no longer needed -- now replace works global without flags
Replace has an alternate form that takes 3 parameters and accepts a string:
function name(str,replaceWhat,replaceTo){
str.replace(replaceWhat,replaceTo,"g");
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

How can I replace '/' in a Javascript string with another character [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript replace all / with \ in a string?
I have a date='13/12/2010' I want to replace this '/' to '_' or something else.
I read this But I do not know how can that applied for my case .
Use a global RegEx (g = global = replace all occurrences) for replace.
date = date.replace(/\//g, '_');
\/ is the escaped form of /. This is required, because otherwise the // will be interpreted as a comment. Have a look at the syntax highlighting:
date = date.replace(///g, '_');
One easiest thing :)
var date='13/12/2010';
alert(date.split("/").join("_")); // alerts 13_12_2010
This method doesn't invoke regular expression engine and most efficient one
You can try escaping the / character like this -
date.replace( /\//g,"_");

Categories

Resources