How to use replaceAll() in Javascript.........................? [duplicate] - javascript

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I am using below code to replace , with \n\t
ss.replace(',','\n\t')
and i want to replace all the coma in string with \n so add this ss.replaceAll(',','\n\t') it din't work..........!
any idea how to get over........?
thank you.

You need to do a global replace. Unfortunately, you can't do this cross-browser with a string argument: you need a regex instead:
ss.replace(/,/g, '\n\t');
The g modifer makes the search global.

You need to use regexp here. Please try following
ss.replace(/,/g,”\n\t”)
g means replace it globally.

Here's another implementation of replaceAll.
String.prototype.replaceAll = function (stringToFind, stringToReplace) {
if (stringToFind === stringToReplace) return this;
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
Then you can use it like:
var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");

Related

How to create a function to split the following string? [duplicate]

This question already has answers here:
What is the shortest function for reading a cookie by name in JavaScript?
(20 answers)
Closed 2 years ago.
I have this string
"G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;
_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5"
And i need some sort of function to split this string given an argument , for example given that my string is text
text.split(";") , will split it into an array separating it by ";"
But i need a function like this
returnText(text , property) that would work like
returnText(text, "_gcl_au") --> returns "someglcau"
You could actually use a regex replacement approach here, for a one-liner option:
function returnText(text, property) {
var term = text.replace(new RegExp("^.*\\b" + property + "=([^;]+)\\b.*$", "gm"), "$1");
return term;
}
var input = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie;_ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(input, "_gcl_au"));
you can use split, just as you tried:
function returnText(text , property){
entries = text.split('; ');
const newEntries = [];
entries.forEach(item => {
let vals = item.split('=');
newEntries[vals[0]] = vals[1]
});
return newEntries[property];
}
const text = "G_ENABLED_IDPS=app; COOKIE_EINF=someCookie; _ga=someGA;_hjid=someHJID; _gcl_au=someglcau; COOKIE_EINF_SESS=somecookie1; _gid=somegid; _hjIncludedInPageviewSample=2; _hjTLDTest=3; _hjAbsoluteSessionInProgress=0; _hjIncludedInSessionSample=1; _gat_UA-124355-12=5";
console.log(returnText(text,'_gcl_au'));

JS get the last dot of a string and return the string after it [duplicate]

This question already has answers here:
String manipulation - getting value after the last position of a char
(8 answers)
Closed 5 years ago.
I have this RegExp below working. But the return is True or False. What I want here is to get the last DOT of a string and return the last string after the DOT. As example below I have image.jpeg.jpeg I want to return the last jpeg. I also try g.match(x) but it gives me an error. g.match is not a function
var x = "image.jpeg.jpeg"
var g = /(.*)\.(.+)/;
alert(g.test(x));
Alternatively, you can use split method like so:
var x = "image.jpeg.jpeg";
var ans = x.split('.').pop();
console.log(ans);
Try this:
var x = "image.jpeg.jpeg"
var g = /(.*)\.(.+)/;
alert(x.match(g)[2]);
match is a method of String (not RegExp), it's argiment RegExp
Try this:
var matches = x.match(g);
if (matches.length === 0) {
console.log('Error');
return;
}
var last = m[m.length - 1]
alert(last);
use this:
var x = "image.jpeg.jpeg"
var g = /\.([0-9a-z]+)$/i;
console.log(x.match(g)[0]); //with a dot
console.log(x.match(g)[1]); //extension only

How to parse url to get desired value [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 6 years ago.
How can I parse a link in jqueryjavascript?
I have the url (some path)/restaurantProfile.php?id=51
And I want to parse this to only obtain the 51. (keep in mind this needs to be generalized. The id won't obviously be always 51...)
Thanks in advance!
You can split the string at id=:
var url = 'some/path/restaurantProfile.php?id=51';
var id = url.split('id=')[1]; // 51
I forget where I saw this, but here is a nice jquery function you can use for this:
//jQuery extension below allows for easy query-param lookup
(function($) {
$.QueryString = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'))
})(jQuery);
Usage like so:
var restaurantId = $.QueryString["id"];
You can make use of Regular Expression in javascript. RegExp Object provides methods to Match the Regular Expression with a input String.
You can make use of string object split method to split the string by using a separator character.
There is a similar question at How can I get query string values in JavaScript? for more options.
You can use the URLSearchParams API to work with the query string of a URL
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
// get the current url from the browser
var x = new URLSearchParams(window.location.search);
// get the id query param
var id = x.get('id');

How can I do string replace in jquery [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 6 years ago.
I have this code
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(" ", "-");
$("#newsurl").val(res);
});
to replace spaces into dash to get URL like this
wordone-wordtow-wordthree
but i have problem with this code it's just replace first space like this
wordone-wordtow wordthree
How can i solve this problem
You need to do a global match, you can do this with a regex
var res = titleval.replace(/\s/g, "-");
Though String.prototype.replace does support having flags passed, this is deprecated in firefox and already doesn't work in chrome/v8.
Alternate method (if regex is not mandatory) could be to split and join
var res = titleval.split(" ").join("-");
or
var res = titleval.split(/\s+/).join("-");
Use regex with global flag
titleval.replace(/\s/g, "-");
try like this:
$("#title").keyup(function(){
var titleval = $("#title").val();
var res = titleval.replace(/\s+/g, '-');
$("#newsurl").val(res);
});

replace all occurrences in a string [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Fastest method to replace all instances of a character in a string
How can you replace all occurrences found in a string?
If you want to replace all the newline characters (\n) in a string..
This will only replace the first occurrence of newline
str.replace(/\\n/, '<br />');
I cant figure out how to do the trick?
Use the global flag.
str.replace(/\n/g, '<br />');
Brighams answer uses literal regexp.
Solution with a Regex object.
var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');
TRY IT HERE : JSFiddle Working Example
As explained here, you can use:
function replaceall(str,replace,with_this)
{
var str_hasil ="";
var temp;
for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
{
if (str[i] == replace)
{
temp = with_this;
}
else
{
temp = str[i];
}
str_hasil += temp;
}
return str_hasil;
}
... which you can then call using:
var str = "50.000.000";
alert(replaceall(str,'.',''));
The function will alert "50000000"

Categories

Resources