String.replace with special characters noting working - javascript

I have spent several hours trying to figure out what is going on here looking at stack overflow and elsewhere and I cannot figure out what is going on. I would really appreciate any help!!
I need to make document.write('< /div>'); go to -> < /div>
I've simplified it down to the simplest possible case with the html example below.
<script>
var str = "document.write('</div>');";
str = str.replace("/document.write/g","");
console.log(str); //</div>
</script>

Exclude the quotes and it works. It is being interpreted as a string literal because of the quotes, whereas a regular expression literal is expressed between plain /s.
Also, . needs to be escaped or it matches any other single character.
<script>
var str = "document.write('</div>');";
str = str.replace(/document\.write/g,"");
console.log(str); //</div>
</script>

String.prototype.replace() accepts either a string or a regex. If you are going with a string this should be:
var str = "document.write('</div>');";
str = str.replace("document.write","");
console.log(str);

Related

Javascript: add a character to a string containing a specific word

If I have the following string: table.row.columns.values.many. I am looking to add character * after values.
So expected output would be: table.row.columns.values*.many .
If there is no "values" in string then string should stay the same.
Please use this code.
let str = "table.row.columns.values.many"
str = str.replace("values", "values*");
console.log(str);
You can use also "replaceAll" if you want to replace all "values".
I think this works nice for you, really simple, and easy way
var str = "table.row.columns.values.many";
str = str.replace("values", "values*")
console.log(str)

How to replace "\" with "\\" from a string using Javascript?

I tried mystring.replace(/\\/g,"\\") but that didn't work.
Can someone advise me how to do this replacement?
Example: String = "C:\Users\Test\FileName"
When I replace \ with \\, I need to see a result as follows:
C:\\Users\\Test\\FileName
Inside string \-backslash is used to escape the following character. In the string, "C:\Users\Test\FileName" also backslash is used as escape sequence and actual string is "C:UsersTestFileName"
var str = "C:\Users\Test\FileName";
console.log(str);
To make this correct, the backslashes in the string should already escaped.
var str = "C:\\Users\\Test\\FileName";
var str = "C:\\Users\\Test\\FileName";
console.log(str);
The regex can now be used to double the backslashes
str.replace(/\\/g, '\\\\');
var str = "C:\\Users\\Test\\FileName";
console.log(str);
console.log(str.replace(/\\/g, '\\\\'));
Try this, use raw string,String.raw() method is a tag function of template literals
String.raw`\"`.replace(/\"/g, '\\"');
or,if first one isn't work,try this :) hope this will be helped to you
String.raw\".replace(/\\"/g, '\\"');

JavaScript split().join() thousands separator replacement for .replace() for use on eBay

I use this for comma separated thousands on my site, works great...
str.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
I'm trying to implement a similar method for ebay using split().join(), since eBay have banned the usage of .replace(), any solution?
I tried using the same regx inside split(), but thus far it has not worked the same way.
Thanks.
maybe you can try to use search() to get the index of the string and remove the characters for the given index.
var pre_string = str.substing(0, found_index);
var post_string = str.substing(found_index + 3);
var replaced_string = pre_string + post_string;
("100,00,0").split(',').join(''); //"100000"
Something like this?
parseInt( ("100,00,0").split(',').join('') ,10); //100000
I think you are referring to:
Javascript .Replace Alternative
In there the code (by WereWolf - The Alpha) is:
String.prototype.fakeReplace=function(str, newstr) {
return this.split(str).join(newstr);
};
var str="Welcome javascript";
str=str.fakeReplace('javascript', '');
alert(str); // Welcome
So, your:
str.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
Becomes:
str.myReplace(/\B(?=(\d{3})+(?!\d))/g, ",");
How?
because .split(STR) splits the string by STR (removing STR in process) into a two element array (or more), and rejoins it with .join(NEWSTR) which places NEWSTR inbetween the two strings in array.
"hello STR world" --.split(STR)--> ["hello "," world"] --.join(NEWSTR)--> "hello NEWSTR world"

RegEx for WordPress file

I am trying to recognize a string like this one: file=2013/08/something_320x480.jpg and to replace it in JavaScript.
Here is my regex:
newStr = str.replace('/file=\d+\/\d+\/.+\d+x\d+.jpg/', 'irrelevant');
I also tried
newStr = str.replace('/file=.+\.jpg/', 'irrelevant');
However, my string is never replaced. What am I doing wrong?
The regexp literal does not take apostrophes.
Try:
newStr = str.replace(/file=\d+\/\d+\/.+\d+x\d+.jpg/, 'irrelevant');
Are you sure the file is set as you say it is? I just tried your example in the console and it works...
> var a = "file=2013/08/something_320x480.jpg"
undefined
> a.replace(/^file=\d+\/\d+\/.+\d+x\d+.jpg$/, 'irrelevant');
"irrelevant"
Update: I didn't spot that you had apos' in your regex, well spotted #Taemyr

Simple Javascript string manipulation

I have a string that will look something like this:
I'm sorry the code "codehere" is not valid
I need to get the value inside the quotes inside the string. So essentially I need to get the codehere and store it in a variable.
After some researching it looks like I could loop through the string and use .charAt(i) to find the quotes and then pull the string out one character at a time in between the quotes.
However I feel there has to be a simpler solution for this out there. Any input would be appreciated. Thanks!
You could use indexOf and lastIndexOf to get the position of the quotes:
var openQuote = myString.indexOf('"'),
closeQuote = myString.lastIndexOf('"');
Then you can validate they are not the same position, and use substring to retrieve the code:
var code = myString.substring(openQuote, closeQuote + 1);
Regex:
var a = "I'm sorry the code \"codehere\" is not valid";
var m = a.match(/"[^"]*"/ig);
alert(m[0]);
Try this:
var str = "I'm sorry the code \"cod\"eh\"ere\" is not valid";
alert(str.replace(/^[^"]*"(.*)".*$/g, "$1"));
You could use Javascript's match function. It takes as parameter, a regular expression. Eg:
/\".*\"/
Use regular expressions! You can find a match using a simple regular expressions like /"(.+)"/ with the Javascript RegExp() object. Fore more info see w3schools.com.
Try this:
var msg = "I'm sorry the code \"codehere\" is not valid";
var matchedContent = msg.match(/\".*\"/ig);
//matchedContent is an array
alert(matchedContent[0]);
You should use a Regular Expression. This is a text pattern matcher that is built into the javascript language. Regular expressions look like this: /thing to match/flags* for example, /"(.*)"/, which matches everything between a set of quotes.
Beware, regular expressions are limited -- they can't match nested things, so if the value inside quotes contains quotes itself, you'll end up with a big ugly mess.
*: or new RegExp(...), but use the literal syntax; it's better.
You could always use the .split() string function:
var mystring = 'I\'m sorry the code "codehere" is not valid' ;
var tokens = [] ;
var strsplit = mystring.split('\"') ;
for(var i=0;i<strsplit.length;i++) {
if((i % 2)==0) continue; // Ignore strings outside the quotes
tokens.push(strsplit[i]) ; // Store strings inside quotes.
}
// Output:
// tokens[0] = 'codehere' ;

Categories

Resources