Javascript Replace Regex - javascript

Ok, I'm actually trying to replace text.
Basically, I am needing to replace all instances of this: | with a blank string ''
However, this isn't working:
langName = langName.replace(/|/g, '');
Also, would be best if I could also replace all of these instances within the string, with a '' also:
" double quote
' single quote
/ back slash
\ forward slash
And any other html entity characters. Arrggg.
Can someone please help me here? Perhaps it can be turned into a String.prototype function so I can use it more than once?
Thanks :)

You need to escape | with \ like:
langName = langName.replace(/\|/g, '');
Test Case:
var langName = 'this| is | some string';
langName = langName.replace(/\|/g, '');
alert(langName);
Output:
this is some string
The reason why you need to escape | is that it is special regex character.
Alternatively, you could also use split and join like this:
langName = langName.split('|').join('');

Related

How to fix 'missing) after argument list' error in Javascript

Why is this giving me this error?
<script>
function loadImg() {
var imageChosen = document.getElementById('imageChosen').value.replace("C:\fakepath\","");
alert(imageChosen);
document.getElementById('image').src = imageChosen;
}
</script>
I expect the image with id "image" to show the chosen image.
The value in your call to replace() is not escaped properly.
The value should instead be:
"C:\\fakepath\\",""
Read more about escaping strings here
The problem is due to the escape string character \ (backslash)
When using strings in Javascript we may escape some character in the string. For example a break line (\n) or even a "(double quotes) when declaring the string or even an backslash \ need a escape.
Examples:
x = "my \\" // Will output as the same as "my \"
z = "my \"quotes\" // Will output as 'my "quotes" '

Javascript (Regex): How do i replace (Backslash + Double Quote) pairs?

In Javascript, i want the below original string:
I want to replace \"this\" and \"that\" words, but NOT the one "here"
.. to become like:
I want to replace ^this^ and ^that^ words, but NOT the one "here"
I tried something like:
var str = 'I want to replace \"this\" and \"that\" words, but NOT the one "here"';
str = str.replace(/\"/g,"^");
console.log( str );
Demo: JSFiddle here.
But still .. the output is:
I want to replace ^this^ and ^that^ words, but NOT the one ^here^
Which means i wanted to replace only the \" occurrences but NOT the " alone. But i cannot.
Please help.
As #adeneo's comment, your string was created wrong and not exactly like your expectation. Please try this:
var str = 'I want to replace \\"this\\" and \\"that\\" words, but not the one "here"';
str = str.replace(/\\\"/g,"^");
console.log(str);
You can use RegExp /(")/, String.prototype.lastIndexOf(), String.prototype.slice() to check if matched character is last or second to last match in input string. If true, return original match, else replace match with "^" character.
var str = `I want to replace \"this\" and \"that\" words, but NOT the one "here"`;
var res = str.replace(/(")/g, function(match, _, index) {
return index === str.lastIndexOf(match)
|| index === str.slice(0, str.lastIndexOf(match) -1)
.lastIndexOf(match)
? match
: "^"
});
console.log(res);
The problem with String.prototype.replace is that it only replaces the first occurrence without Regular Expression. To fix this, you need to add a g and the end of the RegEx, like so:
var mod = str => str.replace(/\\\"/g,'^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');
A less effective but easier to understand to do what you wanted is to split the string with the delimiter and then join it with the replacement, like so:
var mod = str => str.split('\\"').join('^');
mod('I want to replace \\"this\\" and \\"that\\" words, but NOT the one "here"');
Note: You can wrap a string with either ' or ". Suppose your string contains ", i.e. a"a, you will need to put an \ in front of the " as "a"a" causes syntax error. 'a"a' won't cause syntax error as the parser knows the " is part of the string, but when you put a \ in front of " or any other special characters, it means the following character is a special character. So 'a\"a' === 'a"a' === "a\"a". If you want to store \, you will need to use \ regardless of the type of quote you use, so to store \", you will need to use '\\"', '\\\"' or "\\\"".

How to escape characters in a string

Consider below response of ajax-
function validateVar(){
$.ajax({
url:"abc.do",
datatype:"text",
success:function(response){
alert(response); //"asdjakd"fsd'f'fsf"s'dfs'df"fsdf"fsfsf""
}
});
}
I want to escape all occurrences of quotes in the response.
JSFIDDLE: https://jsfiddle.net/ashwyn/3w0aj5z7/
You can use the backslash to escape a character \. So to store your string in a variable we can write it like this.
var v = "asdjakd\"fsd\'f\'fsf\"s\'dfs\'df\"fsdf\"fsfsf";
You can't programmatically escape a string to make it valid JavaScript.
It has to be valid JavaScript to get through the JavaScript parser before it can be modified by JavaScript.
You have to fix it in the source code.
The \ character starts an escape sequence in a JavaScript string literal:
var v = "asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf";
You can use backslash to solve this
You need to add backslash for same type inverted commas(single or double).
function validateVar(){
var v = "asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf";
alert(v);
}
Update the fiddle as well, check here :: https://jsfiddle.net/3w0aj5z7/1/
You need to escape the double quotationmark " with backslash \
Your string should look like this:
"asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf"
You can include the string between '' or "" .
Then you must say to the variable where quotes aren't the closing ones with \ before it.
In this case:
var v = ' "asdjakd"fsd\'f\'fsf"s\'dfs\'df"fsdf"fsfsf" ';
before ' quote
or
var v = " \"asdjakd\"fsd'f'fsf\"s'dfs'df\"fsdf\"fsfsf\" ";
before " quotes

Regex that only works on browser tester

I've tested my regex on Regex testers and it worked, but I didn't get it to work on my code.
var mail = "chdelfosse#gmail.com";
var regExp = new RegExp("#(.*?)\.");
document.write(regExp.exec(mail)) ;
I get this result :
#g,
I tried to add a backslash before the dot, and I got this :
#gmail.,gmail
I also wanted to remove the "#" and the "." from the email, so I tried to use " (?:#) ", but I didn't get it to work (on Regex testers).
It's my first time trying to use Regex, and I don't get it.
Why is there a comma ?
You can use this regex to get the domain name:
/#(.+)\./
Live DEMO
Faster than regex:
var emailAddress = "my.email#gmail.com";
var array_email = emailAddress.split("#");​​
alert('Account: ' + array_email[0] +'; Domain: ' + array_email[1]);​​​​​​​​​​​​​​​​​​​​​​​​​​
A couple things to do differently:
You need to double escape your backslash in the string so that one backslash still remains for the RegExp constructor or switch to the /regex here/ syntax.
If you want just the subgroup in the parens, you need to refer to that specific subgroup.
Here's the code:
var mail = "chdelfosse#gmail.com";
console.log(mail.match(/#(.*?)\./)[1]);

How to replace all the \ from a string with space in javascript?

For example:
var str="abc\'defgh\'123";
I want to remove all the \ using Javascript. I have tried with several functions but still can't replace all the forward slashes.
I've posted a huuuge load of bollocks on JS and multiple replace functionality here. But in your case any of the following ways will do nicely:
str = str.replace('\\',' ');//Only replaces first occurrence
str = str.replace(/\\/g,' ');
str = str.split('\\').join(' ');
As #Guillaume Poussel pointed out, the first approach only replaces one occurrence of the backslash. Don't use that one, either use the regex, or (if your string is quite long) use the split().join() approach.
Just use the replace function like this:
str = str.replace('\\', ' ');
Careful, you need to escape \ with another \. The function returns the modified string, it doesn't modify the string on which it is called, so you need to catch the return value like in my example! So just doing:
str.replace('\\', ' ');
And then using str, will work with the original string, without the replacements.
str="abc\\'asdf\\asdf"
str=str.replace(/\\/g,' ')
You want to replace all '\' in your case, however, the function replace will only do replacing once if you use '\' directly. You have to write the pattern as a regular expression.
See http://www.w3schools.com/jsref/jsref_replace.asp.
Try:
string.replace(searchvalue,newvalue)
In your case:
str.replace('\\', ' ');
Using string.replace:
var result = str.replace('\\', ' ');
Result:
"abc 'defgh '123"

Categories

Resources