Javascript find and replace a set of characters? - javascript

I have a string and I need to replace all the ' and etc to their proper value
I am using
var replace = str.replace(new RegExp("[']", "g"), "'");
To do so, but the problem is it seems to be replacing ' for each character (so for example, ' becomes '''''
Any help?

Use this:
var str = str.replace(/'/g, "'");
['] is a character class. It means any of the characters inside of the braces.
This is why your /[']/ regex replaces every single char of ' by the replacement string.
If you want to use new RegExp instead of a regex literal:
var str = str.replace(new RegExp(''', 'g'), "'");
This has no benefit, except if you want to generate regexps at runtime.

Take out the brackets, which makes a character class (any characters inside it match):
var replace = str.replace(new RegExp("'", "g"), "'");
or even better, use a literal:
var replace = str.replace(/'/g, "'");
Edit: See this question on how to escape HTML: How to unescape html in javascript?

Rather than using a bunch of regex replaces for this, I would do something like this and let the browser take care of the decoding for you:
function HtmlDecode(s) {
var el = document.createElement("div");
el.innerHTML = s;
return el.innerText || el.textContent;
}

Related

Need to replace a string from a long string in javascript

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

Regular Expression to replace variable with variable

I have some string that looks like this:
var string = popupLink(25, 'Any string')
I need to use a regular expression to change the number inside (note that this is a string inside of a larger string so I can't simply match and replace the number, it needs to match the full pattern, this is what I have so far:
var re = new RegExp(`popupLink\(${replace},\)`, 'g');
var replacement = `popupLink(${formFieldInsert.insertId},)`;
string = string.replace(re, replacement);
I can't figure out how to do the wildcard that will maintain the 'Any String' part inside of the Regular Expression.
If you are looking for a number, you should use \d. This will match all numbers.
For any string, you can use lazy searching (.*?), this will match any character until the next character is found.
In your replacement, you can use $1 to use the value of the first group between ( and ), so you don't lose the 'any string' value.
Now, you can simply do the following:
var newNumber = 15;
var newString = "var string = popupLink(25, 'Any string')".replace(/popupLink\(\d+, '(.*?)'\)/, "popupLink(" + newNumber + ", '$1')");
console.log(newString);
If you just need to change the number, just change the number:
string = string.replace(/popupLink\(\d+/, "popupLink(" + replacement);
Example:
var str = "var string = popupLink(25, 'Any string')";
var replacement = 42;
str = str.replace(/popupLink\(\d+/, "popupLink(" + replacement);
console.log(str);
If you really do have to match the full pattern, and "Any String" can literally be any string, it's much, much more work because you have to allow for quoted quotes, ) within quotes, etc. I don't think just a single JavaScript regex can do it, because of the nesting.
If we could assume no ) within the "Any String", then it's easy; we just look for a span of any character other than ) after the number:
str = str.replace(/(popupLink\()\d+([^)]*\))/, "$1" + replacement + "$2");
Example:
var str = "var string = popupLink(25, 'Any string')";
var replacement = 42;
str = str.replace(/(popupLink\()\d+([^)]*\))/, "$1" + replacement + "$2");
console.log(str);

Replace spaces with unedrscores in entire string

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

Replace a substring with javascript

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

javascript string manipulation

I would like to modify my strings so i can replace the character ' ' with '_' using JS,for example "new zeland"=>"new_zeland"
how can i do that?
var str = 'new zealand';
str = str.replace(/\s+/g, '_');
You could use Rob's code, but it uses a regular expression to find the space, while it would be faster to just search for a literal space:
var string = 'new zealand';
var newString = string.replace(' ', '_');

Categories