Javascript string replace() method malfunctioning for dots and commas - javascript

I want to replace a text by using the user input values but for the below script dots and commas are malfunctioning when replacing. I tried (/\x/) method but it's not working, maybe because it's a value. So, how can I execute output more accurately?
function myFunction() {
var str = document.getElementById("text").value;
var x = new RegExp(document.getElementById("x").value, "g");
var y = document.getElementById("y").value;
var txt = str.replace(x, y);
document.getElementById("newText").innerHTML = txt;
}
function reset() {
document.getElementById("text").value = "";
}
example:
text = ..........a.a.a..a..a..aaaaaa..a.a.
x = ..a
y = B
output = ........B.BBBBBaaB.a.
but output should be
........B.a.aBBBaaaaaB.a.
(Sorry for the unprofessional example...)
I am just now learning JS and not a professional and I'm trying to make a replacer web page using JS like in MS Notepad where you can press ctrl+H and replace any word or letter.

You're looking for RegExp.escape, unlucky for you - the smart people at the JavaScript technical committee decided to postpone its inclusion in the standard because of an edge case you, or anyone else will likely never run into.
if(!RegExp.escape){
RegExp.escape = function(s){
return String(s).replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
};
}
Then, you can call it on a value and it'll escape it for use in new RegExp:
var raw = document.getElementById("x").value;
var x = new RegExp(RegExp.escape(raw), "g");

You want this regex - [.]{2}[a] or [.][.][a].
Two dots mandatory with trailing a. And it should be of 3 characters.

Related

reg expression created from variable not working in .replace()

I'm doing a coding challenge that wants us to create a function that finds and replaces a word in a sentence. I define the reg expression like this
//"before" is the parameter with the word to be replaced
var regRep = '/'+before+'/gi';
and I'm using it like this
//"str" is the sentence to search and prepAfter" is a variable with the replacement word.
var newStr = str.replace(regRep, prepAfter);
when returning newStr I get the original str without any modifications. I went through and console.log()ed each of my variables and chunks of logic and the replace() method is the only thing not working as it's suppose to. Here's the entire function.
function myReplace(str, before, after) {
var prepAfter = "";
var caseCheck = before.charAt(0);
var regRep = '/'+before+'/gi';
if(caseCheck === caseCheck.toUpperCase()){
var firstLetter = after.substr(0,1).toUpperCase();
var wordLength = after.length -1;
var remWord = after.substr(1,wordLength);
prepAfter = firstLetter.concat(remWord);
}
else{ prepAfter = after; }
var newStr = str.replace(regRep, prepAfter);
return newStr;
}
What am I missing?
var regRep = new RegExp(before, 'gi');
If you pass a string to replace() (as you did), it will look for the actual string.
Note: if before is just a word in your case, you might not even need a regex, just passing it to replace() as-is could do. Depends on whether or not you need to check things like whitespace before and after.

using multiple .replace calls on an array of variables in Javascript / jQuery

I am working on a tool that would receive text that has been copied from a word document, and return an html output for copy/paste into an email client for email marketing.
During this process, one of the steps the tool needs to handle is the replacement of special characters within the copied values. The output needs to show the encoded values so when they are copied into the email client, they render accordingly during the mail send process
The problem is that there are multiple inputs the user can populate and right now the code is VERY WET... I want to set up the tool to be a little cleaner, and not repeat the code as often.
Currently the input is given to the tool via a prompt();
I am taking that input and replacing the special characters ™, ®, Ø, ´, ”, ‟ and others (partial list given for this example) as needed:
JS (Commented Version)
msg2 = prompt("enter text here");
//long version to tag each replacement with it's identifying name
msg2 = msg2.replace(/[\u0027]/g, '''); // Apostrophe ´
msg2 = msg2.replace(/[\u2122]/g, '™'); // trademark ™
msg2 = msg2.replace(/[\u00AE]/g, '®'); // R-Ball ®
msg2 = msg2.replace(/[\u201c]/g, '"'); // Left Double Quote ‟
msg2 = msg2.replace(/[\u201D]/g, '"'); // Right Double Quote ”
msg2 = msg2.replace(/[\u2018]/g, '''); // Left Single Quote ‛
msg2 = msg2.replace(/[\u2019]/g, '''); // Right Single Quote ’
msg2 = msg2.replace(/[\u2022]/g, 'ߦ') // Bullet •
JS (Short Version)
msg2 = prompt("enter text here");
msg2 = msg2.replace(/[\u0027]/g, ''').replace(/[\u2122]/g,
'™').replace(/[\u00AE]/g, '®').replace(/[\u201c]/g,
'"').replace(/[\u201D]/g, '"').replace(/[\u2018]/g,
''').replace(/[\u2019]/g, ''').replace(/[\u2022]/g,
'ߦ');
BUT... I need to run this same replacement on a number of prompts. I don't want to repeat this in the code a bunch of times with each of the variables changing as needed.
What I would rather do is create a function to handle the replacement, and then simply create an array of the variables and run the function on the array...
Example
function txtEncode () {
...replacment code here...
}
var inputTxt = [msg1, msg2, msg3...];
for (var i=0; i < inputTxt.length; i++){
txtEncode(i)
}
Just make an array with replacement pairs:
var replacements = [ ["&", "&"], ["'", """] etc
and apply them one by one:
replacements.forEach(function(pair) {
msg = msg.split(pair[0]).join(pair[1]);
});
split/join is better to replace literal strings than .replace which is intended for use with regular expressions.
Also, your encoding doesn't look right, &#174; will be displayed as ®, not as ®
You can use a global find/replace function and extend the string prototype, I have this code in one of my fiddles, but I can't find the origin.
Code:
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
};
var msg2 = 'demo \u0027'
var find = ["\u0027"];
var replace = ["&#39;"];
msg2 = msg2.replaceArray(find, replace);
Demo: http://jsfiddle.net/IrvinDominin/YQKwN/
Add a method to the String object for your code.
String.prototype.myCleanString = function(){
return this.replace(/[\u0027]/g, '&#39;')
.replace(/[\u2122]/g,'&#153;')
.replace(/[\u00AE]/g, '&#174;')
.replace(/[\u201c]/g, '&#34;')
.replace(/[\u201D]/g, '&#34;')
.replace(/[\u2018]/g, '&#39;')
.replace(/[\u2019]/g, '&#39;')
.replace(/[\u2022]/g, '&#2022;')
.replace(/foo/g, 'bar');
}
Call as needed... http://jsfiddle.net/XKHNt/

replace() with RegExp on array elements

I want to write a JavaScript function which converts some simple BBcode Tags like [red] [/red] to Html-Tags. I think the replace() function is the best way to do it. I wrote a simple testfunction to try it, but it does not seem to work.
/**
* #function
* #description Replaces the bb-tags with html-tags
*/
function bbToHtml(form) {
debugger
var text = form.text.value;
bbTags = new Array("[red]", "[yellow]", "[green]", "[/red]", "[/yellow]", "[/green]");
htmlTags = new Array("<font color='red'>", "<font color='yellow'>", "<font color='green'>", "</font>", "<font>", "</font>");
for (var i = 0; i < bbTags.length; i++) {
var re = new RegExp(bbTags[i], "g");
text = text.replace(re, htmlTags[i]);
}
alert(text);
}
It should convert "[red]hello[/red]" to "<font color='red'>hello</font>", but it just gives me a weird string.
What is wrong? I think this has something to do with my regular expression.
[ and ] have special meaning in regular expressions and need to be escaped, moreover you do not need regular expressions the way you've written your code and can just do:
function bbToHtml(form) {
debugger
var text = form.text.value;
bbTags = new Array("[red]", "[yellow]", "[green]", "[/red]", "[/yellow]", "[/green]");
htmlTags = new Array("<font color='red'>", "<font color='yellow'>", "<font color='green'>", "</font>", "<font>", "</font>");
for (var i = 0; i < bbTags.length; i++) {
while(text.indexOf(bbTags[i])!==-1){
text = text.replace(bbTags[i], htmlTags[i]);
}
}
alert(text);
}
Just to let you know, you can use array literals so instead of arrays. new Array(comma seperated values) is identical to [comma seperated values] in javascript.
Also, you can use your array like a map in your case, for example:
var bbTagsToHTML = {}
bbTagsToHtml["[red]"] = "<font color='red'>"
and iterate through that.
If you would like you can escape your regular expressions too, please see How do you use a variable in a regular expression? for a function that does that.
You can also do that manually. "[red]" becomes "\[red\]" (the bracket escaped).
just change this line
text = text.replace(re, htmlTags[i]);
into
text = text.replace(bbTags[i], htmlTags[i]);
removing unuseful code.
replace works also on 'normal' (not regex) values as argument.
If you want to do it with regex you can simplify a lot. No arrays or loops:
var str = '[red]foo[/red] hello world [blue]hey[/blue]',
re = /\[(\w+)\](.*)\[\/\1\]/g;
str = str.replace(re, '<font color="$1">$2</font>');
console.log(str);
//^ <font color="red">foo</font> hello world <font color="blue">hey</font>
Also, as a side note, font is rarely used anymore I'd suggest you use a span with a class.

Use JavaScript string operations to cut out exact text

I'm trying to cut out some text from a scraped site and not sure what functions or library's I can use to make this easier:
example of code I run from PhantomJS:
var latest_release = page.evaluate(function () {
// everything inside this function is executed inside our
// headless browser, not PhantomJS.
var links = $('[class="interesting"]');
var releases = {};
for (var i=0; i<links.length; i++) {
releases[links[i].innerHTML] = links[i].getAttribute("href");
}
// its important to take note that page.evaluate needs
// to return simple object, meaning DOM elements won't work.
return JSON.stringify(releases);
});
Class interesting has what I need, surrounded by new lines and tabs and whatnot.
here it is:
{"\n\t\t\t\n\t\t\t\tI_Am_Interesting\n\t\t\t\n\t\t":null,"\n\t\t\t\n\t\t\t\tI_Am_Interesting\n\t\t\t\n\t\t":null,"\n\t\t\t\n\t\t\t\tI_Am_Interesting\n\t\t\t\n\t\t":null}
I tried string.slice("\n"); and nothing happened, I really want a effective way to be able to cut out strings like this, based on its relationship to those \n''s and \t's
By the way this was my split code:
var x = latest_release.split('\n');
Cheers.
Its a simple case of stripping out all whitespace. A job that regexes do beautifully.
var s = " \n\t\t\t\n\t\t\t\tI Am Interesting\n\t\t \t \n\t\t";
s = s.replace(/[\r\t\n]+/g, ''); // remove all non space whitespace
s = s.replace(/^\s+/, ''); // remove all space from the front
s = s.replace(/\s+$/, ''); // remove all space at the end :)
console.log(s);
Further reading: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
var interesting = {
"\n\t\t\t\n\t\t\t\tI_Am_Interesting1\n\t\t\t\n\t\t":null,
"\n\t\t\t\n\t\t\t\tI_Am_Interesting2\n\t\t\t\n\t\t":null,
"\n\t\t\t\n\t\t\t\tI_Am_Interesting3\n\t\t\t\n\t\t":null
}
found = new Array();
for(x in interesting) {
found[found.length] = x.match(/\w+/g);
}
alert(found);
Could you try with "\\n" as pattern? your \n may be understood as plain string rather than special character
new_string = string.replace("\n", "").replace("\t", "");

javascript/jquery shortening a string without cutting word off

say i had the string text = "this is a long string i cant display" i want to trim it down to 10 characters but if it doesnt end with a space finish the word i don't want the string variable to look like this "this is a long string i cant dis" i want it to finish the word until a space occurs. I'm trying this which was suggested by other people but .replace doesn't seem to be working but .length does? I read somewhere that javascript functions don't work inside jquery functions but i still don't understand why .length works
$(document).ready(function(){
$('.article').each(function(index){
var text = $(this).children('p').text()
var maxLength = 6;
var url = $(this).find('.article-link').attr('href');
alert(text.replace(/^(.{1}[^\s]*).*/, "$1"));
var trimmedString = text.substr(0, maxLength);
var text = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")));
//var text = text.substring(0, 80);
//text = text.replace(/^(.{10}[^\s]*).*/, "$1");
});
});
Seo duit, a chara:
var str = "The rain in Spain falls mainly on the plain.";
var l = 10;
while (str.length > l && str.substr(l-1,1) != " ") l++;
alert(str.substr(0,l));
Javascript functions most definitely do work inside jQuery functions. It looks like your regex might be the issue, if the replace function isn't working for you.
This code works:
$(document).ready(function() {
$('.article').each(function(index) {
var text = $(this).children('p').text();
var maxLength = 6;
var reg = new RegExp('^(.{' + maxLength + '}[^\\s]*).*');
alert(text.replace(reg, "$1"));
});
});
Here's a working example

Categories

Resources