Javascript replace string in a string using value from array - javascript

I want to replace string in a paragraph where string may be combination of alphanumeric and slashes.
What i did:
var arrayFind = new Array('s\\if','t\\/');
var arrayReplace = new Array('If','q');
var arrayFindLength = arrayFind.length;
function replaceRightChar(str, parFind, parReplace){
for (var i = 0; i < arrayFindLength; i++) {
regex = new RegExp(parFind[i], "g");
str = str.replace(regex, parReplace[i]);
}
alert(str);
}
var mainData="s\\if t\\/ h\\ s\\";
replaceRightChar(mainData, arrayFind, arrayReplace);
Error:
Uncaught SyntaxError: Invalid regular expression: /s/: \ at end of pattern

My tests do not end up with any error.
You did have a problem with double escaping, though.
Array('s\\if','t\\/');
should be (if I got right what you want)
Array('s\\\\if','t\\\\/');
Working example: jsfiddle
Edit: I still think that the problem is the double escaping. I updated my fiddle to test all the possible combinations.
Essentially I doubled the arrayFind
var arrayFind1 = new Array('s\\if','t\\/');
var arrayFind2 = new Array('s\\\\if','t\\\\/');
and the mainData
var mainData1="s\if t\/ h\\ s\\";
var mainData2="s\\if t\\/ h\\ s\\";
and quadruplicated the call
replaceRightChar(mainData1, arrayFind1, arrayReplace);
replaceRightChar(mainData1, arrayFind2, arrayReplace);
replaceRightChar(mainData2, arrayFind1, arrayReplace);
replaceRightChar(mainData2, arrayFind2, arrayReplace);
I guess the first or the fourth call are what you need

Just for sake of clarity I add another answer instead of editing my existing one. The point is that when the string comes from a textarea it is not really as if it came from var str=...
It is almost the same, but for escaping.
What works in that case is to use regular expressions defined with the /.../g notation and not with the new RegExp('...','g') notation or to double escape things.
Here a working example. The code:
var arrayFindRE = new Array(/s\\if/g,/t\\\//g);
var arrayFindStr = new Array('s\\\\if','t\\\\/');
var arrayReplace = new Array('If','q');
var arrayFindLength = arrayFindRE.length;
function replaceRegExp(str){
for (var i = 0; i < arrayFindLength; i++) {
str = str.replace(arrayFindRE[i], arrayReplace[i]);
}
alert(str);
}
function replaceString(str){
for (var i = 0; i < arrayFindLength; i++) {
var re = new RegExp(arrayFindStr[i],'g');
str = str.replace(re, arrayReplace[i]);
}
alert(str);
}
(here replaceRegExp and replaceString are called with the value of a textarea in the fiddle).

Related

IN Javascript, replace all after second existence of a character or replace all between two characters

javascript, what is the best way to replace following two scenario.
It is possible to use replace and add regex to do this, if yes, how?
I want to convert "aaa.bbb.ccc" TO "aaa.bbb.*"
I want to convert "aaa.bbb.ccc.ddd.eee" TO "aaa.bbb.*.ddd.*"
var map = 'qwertyuiopasdfghjklzxcvbnm'.split('');
var rand = function(){
var len = map.length,
arr = [],
i;
for (i = 0; i < 3; i++){
arr.push(map[Math.floor(Math.random()*len)]);
}
return arr.join('');
};
var randStr = [rand(), rand()];
/* ASSUME above code is how you get random string */
var string = 'aaa.bbb.' + randStr[0] + '.ddd.' + randStr[1];
// use new RegExp() to parse string as regular expression
var regexp = new RegExp(randStr[0] + '|' + randStr[1], 'gi');
console.log(string.replace(regexp, '*'));
Read more about new RegExp() here (easy one), here (detailed one) and here (working example).
You should be able to apply this concept in your code now.

Removing commas unless inside quotes, not using regexp

I am trying to remove commas in a string unless they appear inside quotes.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
mystring = mystring.split(',').join(newchar);// working correctly
document.write(mystring);
Output I have is
this is a test example "i dont know" jumps
Expected output
this is a test example "i, dont know" jumps
A couple of questions. How can I find the index of string so that inside the quotation it will include comma but outside of quotation " it will not include comma ,. I know I have to use indexOf and substring but I don't know how to format it? (No regex please as I'm new to JavaScript and I'm just focusing on the basics.)
Loop through the string, remembering whether or not you are inside a set of quotation marks, and building a new string to which the commas inside quotes are not added:
var inQuotes = false; // Are we inside quotes?
var result = ''; // New string we will build.
for (var i = 0; i < str.length; i++) { // Loop through string.
var chr = str[i]; // Extract character.
var isComma = chr === ','; // Is this a comma?
var isQuote = chr === '"'; // Is this a quote?
if (inQuotes || !isComma) { // Include this character?
if (isQuote) inQuotes = !inQuotes; // If quote, reverse quote status.
result += chr; // Add character to result.
}
}
This solution has the advantage compared to the accepted one that it will work properly even if the input has multiple quotes strings inside it.
This will work, but it's not ideal for all cases. Example: It will not work for a string with more than 2 quotation marks.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
var firstIndex = mystring.indexOf("\"");
var lastIndex = mystring.lastIndexOf("\"");
var substring1 = mystring.substring(0,firstIndex).split(',').join(newchar);
var substring2 = mystring.substring(lastIndex).split(',').join(newchar);
mystring = substring1 + mystring.substring(firstIndex, lastIndex) + substring2;
document.write(mystring);
Some day you need to start using regexp, than regexr.com is your friend. The regexp solution is simple:
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '_';
mystring = mystring.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g).join(newchar);// working correctly
document.write(mystring);

Escape a double quote within a match via Regex

I have a String that holds a number of double quotes and I would like to replace only those which are between certain characters.
Example String:
"XML": "<MyTag>"Value1"</MyTag><MyTag2>Value2</MyTag2>"
I would like the output to be:
"XML": "<MyTag>\"Value1\"</MyTag><MyTag2>Value2</MyTag2>"
I have tried variations of the below in regexr to attempt to match the quotes, but I am unsuccessful:
/<MyTag>(")<\/MyTag>/
/(<MyTag>)"(<\/MyTag>)/
Is it possible to add an escape to the quotes between my tags?
If it's very specific just like you write a simple replace() would be much simpler and demand less resources:
var str = '"XML": "<MyTag>"Value1"</MyTag><MyTag2>Value2</MyTag2>"';
// replace
str = str.replace('<MyTag>"','<MyTag>\\"');
str = str.replace('"</MyTag>', '\\"<MyTag>');
// test
alert(str);
JSFiddle:
https://jsfiddle.net/xbe1x0mz/
var sampleString = '"<MyTag>"value1"</MyTag><MyTag>value2</MyTag>"';
var first = sampleString.replace(/<MyTag>"/g, "<MyTag>\\\"")
var second = sampleString.replace(/"</MyTag>/g, "\\\"<MyTag>")
// second = "<MyTag>\"value1\"</MyTag><MyTag>value2</MyTag>"
Do not manipulate XML data with a regular expression! Especially when doing the thing correctly is so easy:
// Convert XML string to DOM:
var root = new DOMParser().parseFromString(YOUR_XML_DATA, 'text/xml');
// Manipulate all elements you want to:
var all_my_tags = root.querySelectorAll('MyTag');
for (var i = 0, len = all_my_tags.length; i < len; ++i) {
var my_tag = all_my_tags[i];
my_tag.textContent = my_tag.textContent.replace(...);
}
// Convert DOM to an XML string again:
var xml_data = new XMLSerializer().serializeToString(root);
Cf.
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
https://developer.mozilla.org/en-US/docs/Web/API/XMLSerializer

Replace multiple strings with Javascript

I'm trying to transform this string
.jpg,.gif,.png
into this (not dots and space after comma)
jpg, gif, png
I thought that something like PHP's str_replace for arrays in JS will do the trick, so I found this post, and specifically this answer. I tried it but is't not working as expected. I'm getting a blank string... Am I doing something wrong?
JS
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 my_string = ".jpg,.gif,.png";
alert(my_string.replaceArray([".", ","],["", ", "]));
Link to jsfiddle
The first thing you're trying to replace is a period ("."), which is a regular expression for any character. You need to escape it: "\\."
I just did this:
var target = '.jpg,.gif,.png';
target = target.replace(/\\./g, '');
target = target.replace(/,/g, ', ');
I'm sure it can be done more efficiently, but this will get the job done.
You can change your fn to this :
function strToArr(str)
{
var res = str.replace(/\./g, "");
return res.split(",");
}

need a regular expression to search a matching last name

I have a javascript array which holds strings of last names.
I need to loop this array and separate out the last names which match a given string.
var names = ['woods','smith','smike'];
var test = 'smi';
var c = 0;
var result = new Array();
for(var i = 0; i < names.length; i++)
{
if(names[i].match(test))// need regular expression for this
result[c++] = names[i];
}
return result;
name should match the test string even if the test lies within the name. so... mik should match 'Mike' and 'Smike' also.
Any help is really appreciated!
You can create a regex from a string:
var nameRe = new RegExp("mik", "i");
if(names[i].match(nameRe))
{
result.push(names[i]);
}
Make sure to escape regex meta-characters though - if your string may contain them. For example ^, $ may result in a miss-match, and *, ? ) and more may result in an invalid regex.
More info: regular-expressions.info/javascript
You can do this without regex:
if (names[i].toLowerCase().indexOf(test.toLowerCase()) >= 0)
// ...
Javascript string .search is what you're looking for.. You don't even need regex although search supports that too.
var names = ['woods','smith','smike'];
var test = 'smi';
var c = 0;
var result = new Array();
for(var i = 0; i < names.length; i++)
{
if(names[i].toLowerCase().search(test))// need regular expression for this
result.push(names[i]);
}
return result;
You can do this with one regex.
var r = new RegExp(names.join('|'), "igm");
'woods smith'.match(r);
You don't need regex for this, so I'd recommend using string manipulation instead. It's almost (almost!) always better to use string functions instead of regex when you can: They're usually faster, and it's harder to make a mistake.
for(var i = 0; i < names.length; i++)
{
if(names[i].indexOf(test) > -1)
//match, do something with names[i]...
}

Categories