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
Related
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);
Trying to get a filename and have it return a string.
try to turn:
plate-71-winter-hawk-final.jpg
into:
winter hawk final
where plate might also be uppercase. Here is what I have so far, doesn't seem to work
var theRegEx = new RegExp('[Plate|plate]-\d+-(.*).jpg');
var theString = "plate-71-winter-hawk-final.jpg"
var newString = theString.replace(theRegEx, theString);
newString;
Unfortunately, the "Rule #1" doesn't offer a better way:
var newString = theString.replace(/^[Pp]late-\d+-(.*)\.jpg$/, '$1')
.replace(/-/g, ' ');
Take care when you use a string with the object syntax to escape backslahes:
var theRegEx = new RegExp('^[Pp]late-\\d+-(.*)\\.jpg$');
Note that a character class is only a set of characters, you can't use it to put substrings and special regex characters loose their meaning inside it. [Plate|plate] is the same thing than [Pplate|]
You can write it like this too (without string):
var theRegEx = new RegExp(/^[Pp]late-\d+-(.*)\.jpg$/);
Try following script. It's not dependent on length of string as long as it follows standard pattern:
var data = "plate-71-winter-hawk-final.jpg";
var rx = /(?:plate\-\d+\-)(.*)(?=\.)/i;
var match = rx.exec(data);
if(match != null){
data = match[1];
data = data.replace(/\-/g, ' ');
}
console.log(data);
It will print:
winter hawk final
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).
Javascript:
var string = '(37.961523, -79.40918)';
//remove brackets: replace or regex? + remove whitespaces
array = string.split(',');
var split_1 = array[0];
var split_2 = array[1];
Output:
var split_1 = '37.961523';
var split_2 = '-79.40918';
Should I just use string.replace('(', '').replace(')', '').replace(/\s/g, ''); or RegEx?
Use
string.slice(1, -1).split(", ");
You can use a regex to extract both numbers at once.
var string = '(37.961523, -79.40918)';
var matches = string.match(/-?\d*\.\d*/g);
You would probably like to use regular expressions in a case like this:
str.match(/-?\d+(\.\d+)?/g); // [ '37.961523', '-79.40918' ]
EDIT Fixed to address issue pointed out in comment below
Here is another approach:
If the () were [] you would have valid JSON. So what you could do is either change the code that is generating the coordinates to produce [] instead of (), or replace them with:
str = str.replace('(', '[').replace(')', ']')
Then you can use JSON.parse (also available as external library) to create an array containing these coordinates, already parsed as numbers:
var coordinates = JSON.parse(str);
Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);