Replace function of JavaScript don't work - javascript

I have next code in javascript:
csvReport.name = "My New Report";
$scope.filename = csvReport.name.replace(" ", "_");
But I get $scope.filename = My_New Report. Not all spaces replacing.
What is it?

.replace will always replace the first occurence except if you use regular expression like that :
csvReport.name.replace(/ /g, "_");

You can use replace with a regular expression :
"My New Report".replace(/ /g,'_')
Demo

You can use regular expression with a global switch (g) to actually replace all instances, like this:
csvReport.name = "My New Report";
$scope.filename = csvReport.name.replace(/ /g, "_");

Function replace only replace first appearance of first argument. You can use regular expression to replace in whole string.
Try this:
if (!String.replaceAll) {
String.prototype.replaceAll = function(replace, value) {
var regexpStr = replace.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
return this.replace(new RegExp(regExpStr, 'g'), value);
};
}
This way you have additional function that works on whole string.

Related

How to replace a string with square brackets using javascript replace function?

I have a string [TEST][NO CHANGE][TEST][NOW][TEST] in which [TEST] should be replace with 'replaced', and the result should be replaced[NO CHANGE]replaced[NOW]replaced.
I have Tried the following ways, nothing worked.
1. str.replace(/'[TEST]'/g, 'replaced');
2. str.replace(/[TEST]/g, 'replaced');
3. str.replace('/[TEST]/g', 'replaced');
var str = "[TEST][NO CHANGE][TEST][NOW][TEST]";
var resultStr = str.replace(/'[TEST]'/g, 'replaced');
Actual String: [TEST][NO CHANGE][TEST][NOW][TEST]
After Replacing: replaced[NO CHANGE]replaced[NOW]replaced
[] has a special meaning in regex, which means character class, if you want to match [] you need to escape them
var str = "[TEST][NO CHANGE][TEST][NOW][TEST]";
var resultStr = str.replace(/\[TEST\]/g, 'replaced');
console.log(resultStr)
Try to update using Below snippet.
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
var str = "[TEST][NO CHANGE][TEST][NOW][TEST]";
var result = str.replaceAll('\[TEST\]','replaced')
console.log(result);
replaced[NO CHANGE]replaced[NOW]replaced
Src : How to replace all occurrences of a string in JavaScript
Your regular expression in replace is looking for the string '[TEST]' surrounded by those single quotes and is looking to match any of the characters in TEST because you didn't escape the brackets. Try this regular expression instead:
var resultStr = str.replace(/\[TEST\]/g, 'replaced');

How to put a variable in my JS regular expression? [duplicate]

I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps

Apply RegEx replace on all matched values in a CSS stylesheet [duplicate]

I have the following code, which works, but I need to inject some different stuff into the regular expression object (regex2) at runtime. However, text.replace does not seem to like a string object for the regular expression, so how can I make this work?
var regex2 = /\|\d+:\d+/;
document.write("result = " + text.replace(regex2, '') + "<br>");
You can make a regular expression object from a string using the RegExp constructor function:
var regExp = new RegExp(myString); // regex pattern string
text.replace(regExp, '');
Addition to CMS:
The RegExp constructor has an second optional parameter flags
(15.10.4 The RegExp Constructor)
var text = "This is a Test.";
var myRegExp = new RegExp('teST','i');
text.replace(myRegExp,'Example');
// -> "This is a Example."
as Flags you can set
g -> global search (all occurrences)
i -> case insensitive
m -> multiline
var value = "2012-09-10";
value = value.replace(/([0-9]{4})[\/-]([0-9]{2})[\/-]([0-9]{2})/,"$3/$2/$1");
alert(value);
this will show
10/09/2012
you can use eval to,
new RegExp( eval("/"+str+"/i") );
bye...

Replace string with a function of replaced string

I would like to find a performant and elegant solution to this problem :
I need to replace a substring of a string, case insensitively, by a function of what have been replaced.
Example :
var highlight = function(inputString, filterString) {
var regex = new RegExp(filterString, 'gi');
return inputString.replace(regex, '<b>' + filterString + '</b>');
};
highlight('The input', 't');
If your run this in your browser console, you'll get :
"<b>t</b>he inpu<b>t</b>"
My problem is that I'd like to keep the original case of the replaced string. Therefore, the expected result would be :
"<b>T</b>he inpu<b>t</b>"
Any idea ?
Edit: Answer by #georg:
return inputString.replace(regex, '<b>$&</b>');
Just use $& in the replacement, which means "what has been found":
var highlight = function(inputString, filterString) {
var regex = new RegExp(filterString, 'gi');
return inputString.replace(regex, '<b>$&</b>');
};
x = highlight('The input', 't');
document.write("<pre>" + JSON.stringify(x,0,3));
Other $... magic constructs, for the reference:
MDN
$& contains the string matched by the last pattern match.
Please refer
https://msdn.microsoft.com/en-us/library/ie/3k9c4a32%28v=vs.94%29.aspx
for more details.

Multiple Regex on String

How can I apply multiple regexs to a single string?
For instance, a user inputs the following into a text area:
red bird
blue cat
black dog
and I want to replace each carriage return with a comma and each space with an underscore so the final string reads as red_bird,blue_cat,black_dog.
I've tried variations in syntax along the lines of the following so far:
function formatTextArea() {
var textString = document.getElementById('userinput').value;
var formatText = textString.replace(
new RegExp( "\\n", "g" ),",",
new RegExp( "\\s", "g"),"_");
alert(formatText);
}
You can chain the replacements. Every application of the replace method retuns a string, so on that string you can apply replace again. Like:
function formatTextArea() {
var textString = document.getElementById('userinput').value;
var formatText =
textString.replace(/\n/g,",")
.replace(/\s/g,"_");
alert(formatText);
}
There's no need for all these new Regular Expression Objects by the way. Use Regular Expression literals (like /\n/g in the above).
Alternatively you can use a lambda for the replacement
const str = `red bird
blue cat
black dog`;
console.log(str.replace(/[\n\s]/g, a => /\n/.test(a) ? "," : "_"));
formatText = textString.replace(/\n/g,',').replace(/\s/g,'_');
As others have mentioned, chaining is good enough for something as simple as what you're asking. However, if you want this to be more dynamic, you can use a replacer function as the second argument:
function formatTextArea() {
var textString = document.getElementById('userinput').value;
var formatText = textString.replace(/\n|\s/g, function ($0) {
if ($0 === "\n")
return ",";
else if ($0 === " ")
return "_";
}
alert(formatText);
}
Using a replacer function will allow you to be dynamic without having to chain together calls to replace(). It may also be marginally faster (regex parser is invoked only once). Be aware that \s will match more than just the space character, though :-) For the purposes of your question, this would be good enough:
var formatText = textString.replace(/\n|\s/g, function ($0) {
return $0 == "\n" ? "," : "_";
}
Regexp object have their own literal notation, using forward slashes, meaning that backslashes don't have to be escaped. For example, /\n/g is equivalent to new RegExp('\\n','g').
function formatTextArea()
{
var textString = document.getElementById('userinput').value;
textString = textString.replace(/\n/g,",").replace(/\s/g,"_");
alert(textString);
}
var textString = "red blue\nhack bye\ntest rt\n";
var formatText = textString.replace(new RegExp( "\\n", "g" ),",").replace(new RegExp( "\\s", "g"),"_");
alert(formatText);
Include http://phpjs.org/functions/str_replace:527 and then
input = str_replace("\\n", ',', input);
input = str_replace(' ', '_', input);

Categories

Resources