Javascript Regex replace [] [duplicate] - javascript

This question already has answers here:
How can I put [] (square brackets) in RegExp javascript?
(8 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 4 years ago.
I am trying to replace the following in a Regex:-
[company-name]
Using Regex I would expect I could use was to use:-
str.replace(/[company-name]/g, 'Google');
But I know that the regex will replace any matching letter.
How am I able to replace the [company-name] with Google using JS Regex?
Thanks in advance for your help.

But I know that the regex will replace any matching letter.
This is only the case because you have encapsulated your characters in a character class by using [ and ]. In order to treat these as normal characters, you can escape these using \ in front of your special characters:
str.replace(/\[company-name\]/g, 'Google');
See working example below:
const str = "[company-name]",
res = str.replace(/\[company-name\]/g, 'Google');
console.log(res);

You need to escape the starting [ as well, in this case as they are special characters too:
var str = "I am from [company-name]!";
console.log(str.replace(/\[company-name]/gi, "Google"));
str = "[company-name]'s awesome!";
console.log(str.replace(/\[company-name]/gi, "Google"));

you could do it this way :
var txt = "So I'm working at [company-name] and thinking about getting a higher salary."
var pattern = /\[.+\]/g;
console.log(txt.replace(pattern, "Google"))

You should escape special characters like square brackets in this case.
Just use:
str.replace(/\[company-name\]/g, 'Google');

Related

Regular Expression to check Special characters except hypen and forwardslash [duplicate]

This question already has answers here:
Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./
(7 answers)
Closed 3 years ago.
I would like to know regex code to check whether it contains Special characters other than hypen and forwardslash in javascript
function containsSpecialCharacters(str){
var regex = /[~`!#$%\^&*+=\-\[\]\';,/{}|\\":<>\?]/g;
return regex.test(str);
}
var result = containsSpecialCharacters("sample"); // false
var result = containsSpecialCharacters("sample-test"); // false
var result = containsSpecialCharacters("sample++"); // true
var result = containsSpecialCharacters("/sample/test"); // false
You can use a normal regex to search for all ASCII special characters, like this one, and then just remove the hypen and backslash:
/[!$%^&*()_+|~=`{}\[\]:";'<>?,.]/
If you want to avoid any other special character, you just have to remove it from the regex.
You can test this regex here: https://regex101.com/r/gxYiGp/2
If you need to support only English characters, it would be far easier to list the exceptions than those you wish to match:
/[^\w\s\\\-]/.test(myString);
As noted, though, this will fail if you need to support international characters.
you can just negate it so it looks shorter, like this :
[^\s\w-]

Multiple conditions in regex - how to replace both colon and space with dash [duplicate]

This question already has answers here:
Replace multiple characters in one replace call
(21 answers)
Closed 3 years ago.
How to replace both colon and space with dash in regex?
Here's what I've managed to do:
to replace space: replace(/\s+/g, '-'),
to replace colon: replace(/:\s+/g, '-').
How do I merge these expressions?
You could do something like this:
var text = "hello: hey"
console.log(text.replace(/(:|\s+)/g, "-"))
Returns "hello--hey"
Use an alternation [ :]
var input = "Hello World:Goodbye";
console.log(input);
input = input.replace(/[ :]+/g, '-');
console.log(input);
Note that this replaces actual spaces, not all whitespace characters, which your original version using \s does.

Splitting a regex based on spaces but inside brackets [duplicate]

This question already has answers here:
split a string only on spaces that are outside curly braces
(3 answers)
JavaScript regular expression split by space only in certain context
(3 answers)
Closed 4 years ago.
Problem Faced:
I would like to split a string based on spaces groups, but not if they are inside brackets.
Example :
"abc { def ghi Klm} opqr"
should give me
["abc", "{ def ghi Klm}", "opqr"]
Solution Needed:
What is the most readable and most efficient regex in order to do this ?
I know that splitting around spaces can be done like this :
sentence.split(/s+/)
But I don't know how to go further.
Duplicate Resolution
This question was indeed already solved here (though was in C#). Apologizing
You may use this regex for matching:
/{[^}]*}|\S+/g
RegEx Demo
This regex uses an alternation to match a string between curly brackets using {[^}]*} OR matches 1+ non-whitespace characters using \S+.
Code:
const regex = /{[^}]*}|\S+/gm;
const str = `abc { def ghi Klm} opqr`;
let m = str.match(regex);
console.log(m);
In regex there is a kind of "dualism", that the same task
can be achieved using either splitting on a pattern or
matching on its "negation".
In your case, due to some limitations of Javascript flavour of regex,
the matching variant is better. Use: /{[^}]*}|\S+/g to find
matches in your text.
It containt 2 alternatives:
{[^}]*} - opening bracket, a seuence of chars other than }
and }.
\S+ - a non-empty sequence of chars other than space / tab / newline.
Example code, tested on rextester.com, where just print is used
for test printouts:
var txt = 'abc { def ghi Klm} opqr xxx';
var res = txt.match(/{[^}]*}|\S+/g);
print("Length: " + res.length);
for (var j in res) {
print(res[j]);
}

How to match with new RegExp exactly [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 5 years ago.
I have this string:
var str = "https://www.mysite.se/this-match?ba=11"
I need to match it exactly (between / and ?), so only this-match matches, not this-ma or anything (shorter) that is contained in this-match.
I.e:
var myre = new RegExp('\/this-ma\?');
Still matches:
myre.exec(str)[0]
"/this-ma"
How can I avoid that a shorter string contained in this-match does give a match?
The definition of your regex is wrong. You'd think that \? would match literal ? character, instead of being non-greedy modifier. Not true. Quite the opposite, in fact.
var myre = new RegExp('\/this-ma\?');
> /\/this-ma?/
The backslash here works within the string literal, and outputs single ? to regex, which becomes non-greedy modifier. Use the regex literal.
var myre = /\/this-ma\?/

Matching content within a string with one regex [duplicate]

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Simple way to use variables in regex
(3 answers)
Closed 10 years ago.
I am looking for a way to RegEx match for a string (double quote followed by one or more letter, digit, or space followed by another double quote). For example, if the input was var s = "\"this is a string\"", I would like to create a RegEx to match this string and produce a result of [""this is a string""].
Thank you!
Use the RegExp constructor function.
var s = "this is a string";
var re = new RegExp(s);
Note that you may need to quote the input string.
This should do what you need.
s =~ /"[^"]*"/
The regex matches a double quote, followed by some number of non-quotes, followed by a quote. You'll run into problems if your string has a quote in it, like this:
var s = "\"I love you,\" she said"
Then you'll need something a bit more complicated like this:
s =~ /"([^"]|\\")*"/
I just needed a pattern to match a double quote followed by one or more characters(letters, digits, spaces) followed by another double quote so this did it for me:
/"[^"]*"/

Categories

Resources