The usernames used by my organization are in the following format:
i:4#.w|abcd\1231231234.abc
I need to remove the \ and everything before it using JavaScript. I have the following code but because of the escape function of the \ in JS I find that JS simply remove \13 from the string. I have search for hours and haven't been able to find any solution. Here is the current code.
<script type="text/javascript">
window.onload = function () {
document.getElementById('userId').innerHTML ="i:4#.w|abmy\1391251254.abc";
}
</script>
<div>
<span id="userId"></span>
</div>
I need the result to be 1391251254.abc
You can use a regex to extract the last part of your string. It will work event if the string contains more than one backslash.
var string = "i:4#.w|abmy\\1391251254.abc"; //Note the escaped '\'
var regex = /.*?\\(.*)$/;
var match = regex.exec(string);
console.log(match[1]); //1391251254.abc
An alternative is using the function substring along with the function lastIndexOf.
var str = "i:4#.w|abmy\\1391251254.abc"
str = str.substring(str.lastIndexOf('\\') + 1)
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
I want to replace multiple occurences of comment and try like below
JsFiddle
Code:
var str = '<!--#test--><!--#test1-->'
str = str.replace('<!--/g', '').replace('-->/g', '');
alert(str)
Your problem is that you're trying to use a string instead of a regular expression. For example, this works.
var str = '<!--#test-->'
str = str.replace(/<!--/g, '').replace(/-->/g, '');
alert(str)
Plain regex commands need to be inside //.
Also, use the
Disjunction; Alternative | (pipe character)
str = str.replace(/<!--|-->/g, ''); // #test#test1
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))
I want to perform a global replace of string using String.replace in Javascript.
In the documentation I read that I can do this with /g, i.e. for example;
var mystring = mystring.replace(/test/g, mystring);
and this will replace all occurrences inside mystring. No quotes for the expression.
But if I have a variable to find, how can I do this without quotes?
I've tried something like this:
var stringToFind = "test";
//first try
mystring = mystring.replace('/' + stringToFind + '/g', mystring);
//second try, not much sense at all
mystring = mystring.replace(/stringToFind/g, mystring);
but they don't work. Any ideas?
var mystring = "hello world test world";
var find = "world";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "yay")); // alerts "hello yay test yay"
In case you need this into a function
replaceGlobally(original, searchTxt, replaceTxt) {
const regex = new RegExp(searchTxt, 'g');
return original.replace(regex, replaceTxt) ;
}
For regex, new RegExp(stringtofind, 'g');. BUT. If ‘find’ contains characters that are special in regex, they will have their regexy meaning. So if you tried to replace the '.' in 'abc.def' with 'x', you'd get 'xxxxxxx' — whoops.
If all you want is a simple string replacement, there is no need for regular expressions! Here is the plain string replace idiom:
mystring= mystring.split(stringtofind).join(replacementstring);
Regular expressions are much slower then string search. So, creating regex with escaped search string is not an optimal way. Even looping though the string would be faster, but I suggest using built-in pre-compiled methods.
Here is a fast and clean way of doing fast global string replace:
sMyString.split(sSearch).join(sReplace);
And that's it.
String.prototype.replaceAll = function (replaceThis, withThis) {
var re = new RegExp(RegExp.quote(replaceThis),"g");
return this.replace(re, withThis);
};
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
};
var aa = "qwerr.erer".replaceAll(".","A");
alert(aa);
silmiar post
You can use the following solution to perform a global replace on a string with a variable inside '/' and '/g':
myString.replace(new RegExp(strFind, 'g'), strReplace);
Thats a regular expression, not a string. Use the constructor for a RegExp object to dynamically create a regex.
var r = new RegExp(stringToFind, 'g');
mystring.replace(r, 'some replacement text');
Try:
var stringToFind = "test";
mystring = mystring.replace(new RegExp(stringToFind, "g"), mystring);
You can do using following method
see this function:
function SetValue()
{
var txt1='This is a blacK table with BLack pen with bLack lady';
alert(txt1);
var txt2= txt1.replace(/black/gi,'green');
alert(txt2);
}
syntax:
/search_string/{g|gi}
where
g is global case-sensitive replacement
gi is blobal case-insensitive replacement
You can check this JSBIN link
http://jsbin.com/nohuroboxa/edit?html,js,output
If you want variables interpolated, you need to use the RegExp object
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions
Example:
var str = "This is my name";
var replace = "i";
var re = new RegExp(replace, 'g')
str = str.replace(re, 'p');
alert(str);
Dynamic global replace
I came to this thread looking for a slightly more complex solution which isn't answered here. I've now found the answer so I'm going to post it in case anyone else finds it useful.
I wanted to do a dynamic global replace, where the replacement strings are based on the original matches.
For example, to capitalise the first letter of all words (e.g. "cat sat mat" into "Cat Sat Mat") with a global find replace. Here's how to do that.
function capitaliseWords(aString) {
// Global match for lowercase letters following a word boundary
var letters = aString.match(/\b[a-z]/g), i, letterMatch;
// Loop over all matched letters
for( i = 0; i < letters.length; i++ ) {
// Replace the matched letters with upper case versions
letterMatch = new RegExp('\\b'+letters[i]); // EDIT - slight fix
aString = aString.replace(letterMatch, letters[i].toUpperCase());
}
// Return our newly capitalised string
return aString;
}
alert( capitaliseWords("cat sat mat") ); // Alerts "Cat Sat Mat"
WIth modern day linters, they prefer you to regEx literal, so rather than new RegExp it would just be `//
With an example:
'test'.replace(/ /gi, '_')
with the test you are looking to replace inside the regex or the /searchableText/ and then replace text in the second parameter. In my case I wanted to replace all spaces with underscores.
Can you use prototype.js? If so you could use String.gsub, like
var myStr = "a day in a life of a thing";
var replace = "a";
var resultString = myStr.gsub(replace, "g");
// resultString will be "g day in g life of g thing"
It will also take regular expressions. To me this is one of the more elegant ways to solve it. prototypejs gsub documentation