I want to escape : and white space at my regex. I tried that:
var re = new RegExp(':| ', 'g');
var result = $(this).attr("id").replace(re, '\\${1}');
However it doesn't work. This is what I want to do:
Jack Kerouac => Jack\\ Kerouac
Albert:Camus => Albert\\:Camus
How can I do that?
There is no need for braces use $& to get the match within the string and use \\\\ for double slash since \\ produces single slash(one slash is for escaping).
.replace(re, '\\$&');
var str = `Jack Kerouac
Albert:Camus`;
var re = new RegExp(':| ', 'g');
console.log(str.replace(re, '\\$&'));
you can use pattern directly instead of instantiating with RegExp object.
also \\ -> produce one \ (escape), add \\\\
var re = /\:|\s/g;
var val1="fname lname";
var val2="fname:lname";
console.log(val1.replace(re,'\\\\$&'));
console.log(val2.replace(re,'\\\\$&'));
This captures more than one space character:
s.replace( \(:| )+\g, '\\\\' )
You can play with more options here - https://regex101.com/r/WW67KE/1
Related
I have a long string
Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
removable_str2 = 'ab#xyz.com;';
I need to have a replaced string which will have
resultant Final string should look like,
cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
I tried with
str3 = Full_str1.replace(new RegExp('(^|\\b)' +removable_str2, 'g'),"");
but it resulted in
cab#xyz.com;c-c.c_ab#xyz.com;
Here a soluce using two separated regex for each case :
the str to remove is at the start of the string
the str to remove is inside or at the end of the string
PS :
I couldn't perform it in one regex, because it would remove an extra ; in case of matching the string to remove inside of the global string.
const originalStr = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;ab#xyz.com;c_ab#xyz.com;';
const toRemove = 'ab#xyz.com;';
const epuredStr = originalStr
.replace(new RegExp(`^${toRemove}`, 'g'), '')
.replace(new RegExp(`;${toRemove}`, 'g'), ';');
console.log(epuredStr);
First, the dynamic part must be escaped, else, . will match any char but a line break char, and will match ab#xyz§com;, too.
Next, you need to match this only at the start of the string or after ;. So, you may use
var Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
var removable_str2 = 'ab#xyz.com;';
var rx = new RegExp("(^|;)" + removable_str2.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "g");
console.log(Full_str1.replace(rx, "$1"));
// => cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
Replace "g" with "gi" for case insensitive matching.
See the regex demo. Note that (^|;) matches and captures into Group 1 start of string location (empty string) or ; and $1 in the replacement pattern restores this char in the result.
NOTE: If the pattern is known beforehand and you only want to handle ab#xyz.com; pattern, use a regex literal without escaping, Full_str1.replace(/(^|;)ab#xyz\.com;/g, "$1").
i don't find any particular description why you haven't tried like this it will give you desired result cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
const full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
const removable_str2 = 'ab#xyz.com;';
const result= full_str1.replace(removable_str2 , "");
console.log(result);
I have tried replace space's with underscore's(_). Using bellow method's in java script
var stt="this is sample";
var stpp= stt.split(' ').join('_');
var stpp= stt.replace(' ','_');
but it will replace first space with underscore after that it will ignore all spaces.
results like
this_is sample
so how to replace all spaces with ( _ ) in sting using java script.
any one can help me.
Use String#replace with a regular expression using the global flag (g):
var stpp = stt.replace(/ /g, '_');
This:
str.replace(new RegExp(" ","g"),"_")
Or this:
var newstring = mystring.split(' ').join('_');
Is there an easy way to make this string:
(53.5595313, 10.009969899999987)
to this String
[53.5595313, 10.009969899999987]
with JavaScript or jQuery?
I tried with multiple replace which seems not so elegant to me
str = str.replace("(","[").replace(")","]")
Well, since you asked for regex:
var input = "(53.5595313, 10.009969899999987)";
var output = input.replace(/^\((.+)\)$/,"[$1]");
// OR to replace all parens, not just one at start and end:
var output = input.replace(/\(/g,"[").replace(/\)/g,"]");
...but that's kind of complicated. You could just use .slice():
var output = "[" + input.slice(1,-1) + "]";
For what it's worth, to replace both ( and ) use:
str = "(boob)";
str = str.replace(/[\(\)]/g, ""); // yields "boob"
regex character meanings:
[ = start a group of characters to look for
\( = escape the opening parenthesis
\) = escape the closing parenthesis
] = close the group
g = global (replace all that are found)
Edit
Actually, the two escape characters are redundant and eslint will warn you with:
Unnecessary escape character: ) no-useless-escape
The correct form is:
str.replace(/[()]/g, "")
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$1]")
This Javascript should do the job as well as the answer by 'nnnnnn' above
stringObject = stringObject.replace('(', '[').replace(')', ']')
If you need not only one bracket pair but several bracket replacements, you can use this regex:
var input = "(53.5, 10.009) more stuff then (12) then (abc, 234)";
var output = input.replace(/\((.+?)\)/g, "[$1]");
console.log(output);
[53.5, 10.009] more stuff then [12] then [abc, 234]
I'd like a JavaScript regular expression that can match a string either at the start of another string, or after a hyphen in the string.
For example, "milne" and "lee" and "lees" should all match "Lees-Milne".
This is my code so far:
var name = "Lees-Milne";
var text = "lee";
// I don't know what 'text' is ahead of time, so
// best to use RegExp constructor.
var re = RegExp("^" + text | "-" + text, "i");
alert(re.exec(name.toLowerCase()));
However, this returns null. What am I doing wrong?
You could also use:
var re = RegExp("(?:^|-)" + text, "i");
Don't forget to escape regex meta characters in text if it's not an expression it self.
JavaScript has no built in function for that, but you could use:
function quotemeta(str){
return str.replace(/[.+*?|\\^$(){}\[\]-]/g, '\\$&');
}
Need to replace a substring in URL (technically just a string) with javascript.
The string like
http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE
or
http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest
means, the word to replace can be either at the most end of the URL or in the middle of it.
I am trying to cover these with the following:
var newWord = NEW_SEARCH_TERM;
var str = 'http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest';
var regex = /^\S+SearchableText=(.*)&?\S*$/;
str = str.replace(regex, newWord);
But no matter what I do I get str = NEW_SEARCH_TERM. Moreover the regular expression when I try it in RegExhibit, selects the word to replace and everything that follows it that is not what I want.
How can I write a universal expression to cover both cases and make the correct string be saved in the variable?
str.replace(/SearchableText=[^&]*/, 'SearchableText=' + newWord)
The \S+ and \S* in your regex match all non-whitespace characters.
You probably want to remove them and the anchors.
http://jsfiddle.net/mplungjan/ZGbsY/
ClyFish did it while I was fiddling
var url1="http://blah-blah.com/search?par_one=test&par_two=anothertest&SearchableText=TO_REPLACE";
var url2 ="http://blah-blah.com/search?par_one=test&SearchableText=TO_REPLACE&par_two=anothertest"
var newWord = "foo";
function replaceSearch(str,newWord) {
var regex = /SearchableText=[^&]*/;
return str.replace(regex, "SearchableText="+newWord);
}
document.write(replaceSearch(url1,newWord))
document.write('<hr>');
document.write(replaceSearch(url2,newWord))