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

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');

Related

Remove string between two variables

I have a string which has some data with a few special characters, Need to remove the data between the desired special char in JavaScript.
The special char would be obtained in a variable.
var desiredChar = "~0~";
And Imagine this to be the Input string:
~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
So I'm supposed to remove the text in bold.
The desired output is supposed to be-
~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~
I've tried using "Replace" and "Regex", but as the desired character is being passed in a variable and keeps changing I'm facing difficulties.
You can create your own regex based on whatever the bounding character(s) are that contain the text you want removed, and then replace any text that matches that regex with a blank string "".
The JS below should work for your use case (and it should work for multiple occurrences as well):
var originalText = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var desiredChar = "~0~";
var customRegex = new RegExp(desiredChar + ".*?" + desiredChar, "gi");
var processedText = originalText.replace(customRegex, "");
console.log(processedText);
You can build your regex from the constructor with a string input.
var desiredChar = "~0~";
// use the g flag in your regex if you want to remove all substrings between desiredChar
var myRegex = new Regex(desiredChar + ".*" + desiredChar, 'ig');
var testString = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
testString = testString.replace(myRegex, "");
Given input string you can use .indexOf(), .lastIndexOf() and .slice().
Note, OR character | passed to RegExp constructor should be escaped to avoid RegExp created by passing string interpreting | character as OR | within resulting RegExp passed to .replace().
var desiredChar = "~0~";
var str = "~0~1|0|20170807|45|111.00|~0~~1~1|0|20170807|50|666.00|~1~~2~1|0|20170807|55|111.00|~2~";
var not = str.slice(str.indexOf(desiredChar), str.lastIndexOf(desiredChar) + desiredChar.length);
// escape OR `|`
var res = str.replace(new RegExp(not.replace(/[|]/g, "\\|")), "");
console.log(res)
You can use the RegExp object:
var regexstring = "whatever";
var regexp = new RegExp(regexstring, "gi");
var str = "whateverTest";
var str2 = str.replace(regexp, "other");
document.write(str2);
Then you can construct regexstring in any way you want.
You can read more about it at http://www.regular-expressions.info/javascript.html

Replace expression between two punctuation letters in javascript

I have a string like the following,
var str = "abcd-12ad3dgs4g56.com"
I want like the following from this
abcd.com
I have to replace only -*. expression with ..
How do I do this in JavaScript?
Simply try this
str.replace( /-\w+/, "" ); //"abcd.com"
var str = "abcd-12ad3dgs4g56.com"
console.log(str.replace(/-\w+/, ""));
You could use a regular expression with a positive lookahead.
var str = "abcd-12ad3dgs4g56.com";
console.log(str.replace(/-.*(?=\.)/g, ''));

How I can replace a underscore with an space inside a word starting with an special char in javascript?

I have this string:
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}";
And I'm trying to replace the ALL the underscores with spaces for any word starting with exclamation sing (!) so the string should looks like this one:
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap Accessible},currentView:!map}";
I spent a few hours trying to figure out how to do that without success.
Try to use function replacement form (example):
str.replace(/!\w+/g, function(x) { return x.replace(/_/g, ' '); })
Regexp /!\w+/g selects all words started with "!". After that we replace each word x with result of x.replace(/_/g, ' ').
You can use the regex
!([^_]+)_([^]+)
and replace with $1 $2
var str = "{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}";
console.log(str.replace(/!([^_]+)_([^]+)/g, "!$1 $2"));
(![^_]+)_([a-zA-Z0-9]+)
Try this.See demo.
http://regex101.com/r/tF5fT5/57
var re = /(![^_]+)_([a-zA-Z0-9]+)/gm;
var str = '{view-map:{lonField_sad:!Longitude,latField:!Handicap_Accessible},currentView:!map}';
var subst = '$1 $2';
var result = str.replace(re, subst);

how to config RegExp when string contains parentheses

I'm sure this is an easy one, but I can't find it on the net.
This code:
var new_html = "foo and bar(arg)";
var bad_string = "bar(arg)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
sets bad_start to -1 (not found). If I remove the (arg), it runs as expected (bad_start == 8). Is there something I can do to make the (very handy) "new Regexp" syntax work, or do I have to find another way? This example is trivial, but in the real app it would be doing global search and replace, so I need the regex and the "g". Or do I?
TIA
Escape the brackets by double back slashes \\. Try this.
var new_html = "foo and bar(arg)";
var bad_string = "bar\\(arg\\)";
var regex = new RegExp(bad_string, "igm");
var bad_start = new_html.search(regex);
Demo
Your RegEx definition string should be:
var bad_string = "bar\\(arg\\)";
Special characters need to be escaped when using RegEx, and because you are building the RegEx in a string you need to escape your escape character :P
http://www.regular-expressions.info/characters.html
You need to escape the special characters contained in string you are creating your Regex from. For example, define this function:
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
}
And use it to assign the result to your bad_string variable:
let bad_string = "bar(arg)"
bad_string = escapeRegex(bad_string)
// You can now use the string to create the Regex :v:

Convert a string variable to regular expression in java script?

so I am trying to search a string for a sub string, and apparently, I must use regular expressions with the .search function, this is the code I have
var str = items[i].toLowerCase;
var str2 = document.getElementById("input").value.toLowerCase;
var index = str.search(str2);
Obhiously this doesn't work and I get an error, saying str.search is not a function, how would I go about changing these two strings into regular expressions?
thanks
Use this:
new RegExp("your regex here", "modifiers");
Take a look into:
Using a string variable as regular expression
add braces to your function calls:
var str = items[i].toLowerCase();
var str2 = document.getElementById("input").value.toLowerCase();
var index = str.search(str2);
otherwise type of "str" is a function, not result of function execution
your problem is forgetting a set of brackets () -- and as such str and str2 get assigned a function rather than the result of calling that function! Simply change the code:
var str = items[i].toLowerCase();
var str2 = document.getElementById("input").value.toLowerCase();
var index = str.search(str2);
To use an expression in a RegExp constructor:
var re = new RegExp(str, 'g');
will create a regular expression to match the value of str in a string, so:
var str = 'foo';
var re = new RegExp(str, 'i');
is equivalent to the RegExp literal:
var re = /foo/i;
You can use any expression that evaluates to a valid regular expression, so to match foo at the start of a string:
var re = new RegExp('^' + str, 'i');
The only niggle is that quoted characters must be double quoted, so to match whitespace at the end of a string:
var re = new RegExp('\\s+$');
which is equivalent to:
var re = /\s+$/;

Categories

Resources