Replace part of a string in JavaScript - javascript

How can I replace:
var url = "http://localhost:2879/ServiceDonneesArchive.svc/Installations(1002)?$expand=Stations";
by:
var nameInstallation = 1002;
var url = "http://localhost:2879/ServiceDonneesArchive.svc/Installations(nameInstallation)?$expand=Stations";

Why do this the hard way? For this use case, simple concatenation would be very readable:
var nameInstallation = 1002;
var url = 'http://localhost:2879/ServiceDonneesArchive.svc/Installations(' + nameInstallation + ')?$expand=Stations';

Use the .replace() method. To replace any instances of "nameInstallation" in your url variable with "1002":
url = url.replace(/nameInstallation/g, "1002");
Or if you have the replacement value in a variable nameInstallation = 1002:
url = url.replace(/nameInstallation/g, nameInstallation);
EDIT: As pointed out by David Thomas, you probably don't need the g flag on the regular expression that is the first parameter to .replace(). With this "global" flag it will replace all instances of the text "nameInstallation". Without the flag it would replace only the first instance. So either include it or leave it off according to your needs. (If you only need to replace the first occurrence you also have the option of passing a string as the first parameter rather than a regex.)

Try it out this javascript function
// from http://www.codeproject.com/Tips/201899/String-Format-in-JavaScript
String.prototype.format = function (args) {
var str = this;
return str.replace(String.prototype.format.regex, function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");
and use:
var url = "http://localhost:2879/ServiceDonneesArchive.svc/Installations{0}?$expand=Stations";
var nameInstallation = 1002;
var result = url.format(nameInstallation );

Related

Javascript regex match number after string

I have this string
/results?radius=4000&newFilter=true
and I need to replace radius=4000 with radius=n where n is a variable.
How can I use String.replace() method with regex to match that part?
You can use /radius=\d+/ to match "radius=" followed by any number of digits. With this we can use the replace() method to replace it with the desired value:
var str = "/results?radius=4000&newFilter=true";
var replacement = 123;
var newStr = str.replace(/radius=\d+/, "radius=" + replacement);
console.log(newStr);
If you want to get all parameters you can try this :
function getParams(uri) {
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(uri)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
var str='/results?radius=4000&newFilter=true';
str = str.substring(str.indexOf("?"));
params = getParams(str);
console.log(params);
console.log('radius => ', params['radius']);
This answer is from this post: How to get the value from the GET parameters?
It should be as easy as
var str='/results?radius=4000&newFilter=true';
var n = 1234;
str = str.replace(/(radius=)(\d+)/, "$1" + n);
var url = "/results?radius=4000&newFilter=true";
// or window.location.href for current url
var captured = /radius=([^&]+)/.exec(url)[1]; // your 4000
var newValue = 5000;
url = url.replace(captured, newValue);
by this way you can use it to get all your requested parameters too
and it is not decimal binded
ES6 with regex using positive lookbehind
const string = '/results?radius=4000&newFilter=true',
n = '1234',
changeRadius = (radius) => string.replace(/(?<=radius=)\d+/, n);
console.log(changeRadius(n));
/* Output console formatting */
.as-console-wrapper { top: 0; }
changeRadius is function that takes one parameter (radius) and performs replacement.
About the regex: \d+ gets as many digits as possible, (?<=STRING) is a positive lookbehind.
Other regex
Body of changeRadius() function can be replaced with string.replace(/radius=\d+/, 'radius=' + n). It probably has better performance, but original regex is more direct translation of the problem.
You can use capturing without remembering the match to capture only the numerical value after 'radius='.
var url = "/results?radius=4000&newFilter=true";
var radius = 123;
var newUrl = url.replace(/(?:radius=){1}(\d+)/, radius);
console.log(newUrl); // logs '/results?radius=4000&newFilter=true'0
'

Want to get specific value from string

I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#.
I want to get last string vwemployees through RegExp or from any JavaScript function.
Please suggest a way to do this in JavaScript.
You can use the split function:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
str = str.split("#");
str = str[str.length-2];
alert(str);
// Output: vwemployees
The reason for -2 is because of the trailing #. If there was no trailing #, it would be -1.
Here's a JSFiddle.
var s = "...#value#";
var re = /#([^#]+)#^/;
var answer = re.match(s)[1] || null;
if you're sure the string will be separated by "#" then you can split on # and take the last entry... I'm stripping off the last #, if it's there, before splitting the string.
var initialString = "sentrptg2c#appqueue#sentrptg2c#vwemployees#"
var parts = initialString.replace(/\#$/,"").split("#"); //this produces an array
if(parts.length > 0){
var result = parts[parts.length-1];
}
Try something like this:
String.prototype.between = function(prefix, suffix) {
s = this;
var i = s.indexOf(prefix);
if (i >= 0) {
s = s.substring(i + prefix.length);
}
else {
return '';
}
if (suffix) {
i = s.indexOf(suffix);
if (i >= 0) {
s = s.substring(0, i);
}
else {
return '';
}
}
return s;
}
No magic numbers:
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var ar = [];
ar = str.split('#');
ar.pop();
var o = ar.pop();
alert(o);
jsfiddle example

Looking for a regex to parse parameters string for JS

I cannot find out the regex to get param value from the part of query string:
I need to send parameter name to a method and get parameter value as result for string like
"p=1&qp=10".
I came up with the following:
function getParamValue(name) {
var regex_str = "[&]" + name + "=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
// check if result found and return results[1]
}
My regex_str now doesn't work if name = 'p'. if I change regex_str to
var regex_str = name + "=([^&]*)";
it can return value of param 'qp' for param name = 'p'
Can you help me with regex to search the beginning of param name from right after '&' OR from the beginning of a string?
This might work, depending on if you have separated the parameter part.
var regex_str = "(?:^|\&)" + name + "=([^&]*)";
or
var regex_str = "(?:\&|\?)" + name + "=([^&]*)";
Looks like split will work better here:
var paramsMap = {};
var params = string.split("&");
for (var i = 0; i < params.length; ++i) {
var keyValue = params[i].split("=", 2);
paramsMap[keyValue[0]] = keyValue[1];
}
If you desperately want to use a regex, you need to use the g flag and the exec method. Something along the lines of
var regex = /([^=]+)=([^&]+)&?/g;
var paramsMap = {};
while (true) {
var match = regex.exec(input);
if (!match)
break;
paramsMap[match[1]] = match[2];
}
Please note that since the regex object becomes stateful, you either need to reset its lastIndex property before running another extraction loop or use a new RegExp instance.
Change your regex string to the following:
//pass the query string and the name of the parameter's value you want to retrieve
function getParamValue(my_query_string , name)
{
var regex_str = "(?:^|\&)" + name + "\=([^&]*)";
var regex = new RegExp(regex_str);
var results = regex.exec(my_query_string);
try
{
if(results[1] != '')
{
return results[1];
}
}
catch(err){};
return false;
}

Global Replace with js

I have the following string:
[27564][85938][457438][273][48232]
I want to replace all the [ with ''. I tried the following but it didn't work:
var str = '[27564][85938][457438][273][48232]'
var nChar = '[';
var re = new RegExp(nChar, 'g')
var visList = str.replace(re,'');
what am I doing wrong here?
Many thanks in advance.
You need to escape the [ otherwise it is interpreted as the start of a character class:
var nChar = '\\[';
If nChar is a variable (and I assume it is otherwise there would be little point in using RegExp instead of /.../g) then you may find this question useful:
Is there a RegExp.escape function in Javascript?
var string = "[27564][85938][457438][273][48232]";
alert(string.replace(/\[/g, '')); //outputs 27564]85938]457438]273]48232]
I escaped the [ character and used a global flag to replace all instances of the character.
I met this problem today.
The requirement is replace all "c++" in user input string. Because "+" has meaning in Reg expression, string.replace fails.
So I wrote a multi-replace function for js string. Hope this can help.
String.prototype.mreplace = function (o, n) {
var off = 0;
var start = 0;
var ret = "";
while(true){
off = this.indexOf(o, start);
if (off < 0)
{
ret += this.substring(start, this.length);
break;
}
ret += this.substring(start, off) + n;
start = off + o.length;
}
return ret;
}
Example:
"ababc".mreplace("a", "a--"); // returns "a--ba--bc"

How to replace all dots in a string using JavaScript

I want to replace all the occurrences of a dot(.) in a JavaScript string
For example, I have:
var mystring = 'okay.this.is.a.string';
I want to get: okay this is a string.
So far I tried:
mystring.replace(/./g,' ')
but this ends up with all the string replaced to spaces.
You need to escape the . because it has the meaning of "an arbitrary character" in a regular expression.
mystring = mystring.replace(/\./g,' ')
One more solution which is easy to understand :)
var newstring = mystring.split('.').join(' ');
/**
* ReplaceAll by Fagner Brack (MIT Licensed)
* Replaces all occurrences of a substring in a string
*/
String.prototype.replaceAll = function( token, newToken, ignoreCase ) {
var _token;
var str = this + "";
var i = -1;
if ( typeof token === "string" ) {
if ( ignoreCase ) {
_token = token.toLowerCase();
while( (
i = str.toLowerCase().indexOf(
_token, i >= 0 ? i + newToken.length : 0
) ) !== -1
) {
str = str.substring( 0, i ) +
newToken +
str.substring( i + token.length );
}
} else {
return this.split( token ).join( newToken );
}
}
return str;
};
alert('okay.this.is.a.string'.replaceAll('.', ' '));
Faster than using regex...
EDIT:
Maybe at the time I did this code I did not used jsperf. But in the end such discussion is totally pointless, the performance difference is not worth the legibility of the code in the real world, so my answer is still valid, even if the performance differs from the regex approach.
EDIT2:
I have created a lib that allows you to do this using a fluent interface:
replace('.').from('okay.this.is.a.string').with(' ');
See https://github.com/FagnerMartinsBrack/str-replace.
str.replace(new RegExp(".","gm")," ")
For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.
You could try this :
"okay.this.is.a.string".split(".").join("")
Greetings
I add double backslash to the dot to make it work. Cheer.
var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);
replaceAll(search, replaceWith) [MDN]
".a.b.c.".replaceAll('.', ' ')
// result: " a b c "
// Using RegEx. You MUST use a global RegEx.
".a.b.c.".replaceAll(/\./g, ' ')
// result: " a b c "
replaceAll() replaces ALL occurrences of search with replaceWith.
It's actually the same as using replace() [MDN] with a global regex(*), merely replaceAll() is a bit more readable in my view.
(*) Meaning it'll match all occurrences.
Important(!) if you choose regex:
when using a regexp you have to set the global ("g") flag;
otherwise, it will throw a TypeError: "replaceAll must be called with
a global RegExp".
This is more concise/readable and should perform better than the one posted by Fagner Brack (toLowerCase not performed in loop):
String.prototype.replaceAll = function(search, replace, ignoreCase) {
if (ignoreCase) {
var result = [];
var _string = this.toLowerCase();
var _search = search.toLowerCase();
var start = 0, match, length = _search.length;
while ((match = _string.indexOf(_search, start)) >= 0) {
result.push(this.slice(start, match));
start = match + length;
}
result.push(this.slice(start));
} else {
result = this.split(search);
}
return result.join(replace);
}
Usage:
alert('Bananas And Bran'.replaceAll('An', '(an)'));
String.prototype.replaceAll = function(character,replaceChar){
var word = this.valueOf();
while(word.indexOf(character) != -1)
word = word.replace(character,replaceChar);
return word;
}
Here's another implementation of replaceAll. Hope it helps someone.
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:
var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");
Example: I want to replace all double Quote (") into single Quote (') Then the code will be like this
var str= "\"Hello\""
var regex = new RegExp('"', 'g');
str = str.replace(regex, '\'');
console.log(str); // 'Hello'
#scripto's made a bit more concise and without prototype:
function strReplaceAll(s, stringToFind, stringToReplace) {
if (stringToFind === stringToReplace) return s;
for (let index = s.indexOf(stringToFind); index != -1; index = s.indexOf(stringToFind))
s = s.replace(stringToFind, stringToReplace);
return s;
}
Here's how it stacks up: http://jsperf.com/replace-vs-split-join-vs-replaceall/68
String.prototype.replaceAll = function (needle, replacement) {
return this.replace(new RegExp(needle, 'g'), replacement);
};
mystring.replace(new RegExp('.', "g"), ' ');
Simplest way
"Mr.".split('.').join("");
..............
Console
you can replace all occurrence of any string/character using RegExp javasscript object.
Here is the code,
var mystring = 'okay.this.is.a.string';
var patt = new RegExp("\\.");
while(patt.test(mystring)){
mystring = mystring .replace(".","");
}
let a = "once there was a king. spread opeator. let. ver. const.";
let data = a.replaceAll(".","");
Answer : data = "once there was a king spread opeator let ver const";
You need to use replaceAll() method on that string.
var mystring = 'okay.this.is.a.string';
var myNewString = escapeHtml(mystring);
function escapeHtml(text) {
if('' !== text) {
return text.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/\./g,' ')
.replace(/"/g, '"')
.replace(/&#39/g, "'");
}

Categories