JavaScript Surround quotes around a single string in multi lines - javascript

My string is somewhat like this :
<rules>
<transTypeRuleList>
<transType type='stocks'>
<criteria result='401kContribution' priority='0'>
<field compare='contains' name='description'></field>
</criteria>
<criteria result='401kContribution' priority='1'>
<field compare='contains' name='description'></field>
</criteria>
</transType>
</transTypeRuleList>
</rules>
I need to take this and paste it in eclipse as a string , I know eclipse has an option to escape multi line strings and all, but that gives me the string as with "\n \r" Which I don't want .
My ideal string would be just the Double quotes and a + at the end of each line somewhat like this.
var res= "<rules>"+
"<acctTypeRuleList>"+
"<acctTypetype='stocks'>"+
"<criteriaresult='individual'priority='0'>"+
"<fieldcompare='contains'name='accountName'></field>"+
"</criteria>"+
"<criteriaresult='individual'priority='1'>"+
"<fieldcompare='contains'name='accountName'></field>"+
"</criteria>"+
"</acctType>"+
"</acctTypeRuleList>"+
"<transTypeRuleList>"+
"<transTypetype='stocks'>"+
"<criteriaresult='401kContribution'priority='0'>"+
"<fieldcompare='contains'name='description'></field>"+
"</criteria>"+
"<criteriaresult='401kContribution'priority='1'>"+
"<fieldcompare='contains'name='description'></field>"+
"</criteria>"+
"</transType>"+
"</transTypeRuleList>"+
"</rules>";
While preserving the indentation. So I am looking at regex.
So I guess finding ^(.*)$ and replacing with "$1" + should have done the job but it doesn't work .
Have a look at the fiddle. :
Link
Thanks in advance.

This seems to work:
http://regexr.com/38ps2
What I did
added the multiline m switch
removed the empty line in the text. Looks like regexr has problems with that.

I'd try with this:
'var res = "' + xml.replace(/\r?\n\s*/g, '" +\r\n\t"') + '";';
But remember that Javascript does allow multiline strings. Just put a backslash at the end of each line:
"<rules>\
<transTypeRuleList>\
...\
</rules>";

Related

Change Multi line strings to Single line

Hi I have some text in following format,
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545 etc....
Each line break'ed into next line with "Enter". I have nearly 2000 lines of text like this. i want o display the above string to a single line like this.
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545,
686672,
683545 etc..
I think there is some tweak options in CSS for doing this. Is there a way in JavaScript to do this? Actually it is not a requirement for me, am just curious to know how it is done.
Edit:
In My text editor it looks like this,
When i try to run it, this is what i get.
Thats why i want to remove the enter, multiline.......
You can use Regular expression to remove all the linebreaks and replace them using space.
str = str.replace(/\n/g, ' ');
Here, \n will match all the line-breaks, and replace them by space
I have a simple way for this. You can do this without extra code. Just write like this -
var str = "12345,\
234234,\
234324,\
234324,\
234324,\
234234";
now just add a slash
Ok, If you don't want to use the above method then use another plan is -
take inside an array and after that use the join method
var str = [12345,
234234,
234324,
234324,
234324,
234234];
str.join(",");
If we are using ES6, Then we have an elegant way to do this using Backtick -
var str = `12345,
234234,
234324,
234324,
234324,
234234`;
Since your data is already comma separated, you can try to add "[" to the beginning and append " ].toString().replace(/\n/g," ") " to the end of your data to get a single line string like this:
[683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545].toString().replace(/\\n/g," ")
then you get:
"683101,682303,682302,682315,683581,686667,682008,683572,683573,682313,686672,683545"
I hope this helps :)
If all you want is to put those values in one line then, you can set those values as the value of a textarea field. This will allow you to read all those values into a javascript string. Afterward you can apply the regular expression that Tushar suggested.
See the code segment below:
<textarea id="content">
683101,
682303,
682302,
682315,
683581,
686667,
682008,
683572,
683573,
682313,
686672,
683545
</textarea>
Here is the javascript:
var content = $('#content').val();
var content = content.replace(/\n/g, ' ');
console.log(content);

How to remove ' in java script

I have problem in removing ' with (blank and no space). Like Kello's to kellos.
I already tried this-
str = str.replace(/[\']/g, '');
But its not working.
Please help.
It actually does work:
var str = 'aa\'bb\'cc';
alert(str.replace(/'/g,'')); // aabbcc
alert(str.replace(/[\']/g,'')); // aabbcc
You do not need a character class, you just have to mask it if you use single quotes in JavaScript.
Also, keep in mind that ' (U+0027) is different from ’ (U+2019) and must be handled separately.
A Kello's
str.replace(/[{\ },{\'}]/g,"");
result AKellos

Replace all \" with \\" in javascript

I want to replace all \" in my string with \\" (\" in <div style=\"font-size:0.9em\">)
var str = '{"CarID":"Z100","alerts":[{"AlertType":"Head <b>southeast</b> on <b>Tân Hải</b> toward <b>Trường Chinh</b><div style=\"font-size:0.9em\">Pass by nhan cuoi dep (on the right)</div>"}],"customizedLocations":[]}';
str = str.replace(/\"/g, '\\\\"');
I want the output is (\" in style is replaced by \\"):
{"VehicleID":"Z100","alerts":[{"AlertType":"Head <b>southeast</b> on <b>Tân Hải</b> toward <b>Trường Chinh</b><div style=\\"font-size:0.9em\\">Pass by nhan cuoi dep (on the right)</div>"}],"customizedLocations":[]}
But actually I get is (ALL " is replaced by \\"):
{\\"VehicleID\\":\\"Z100\\",\\"alerts\\":[{\\"AlertType\\":\\"Head <b>southeast</b> on <b>Tân Hải</b> toward <b>Trường Chinh</b><div style=\\"font-size:0.9em\\">Pass by nhan cuoi dep (on the right)</div>\\"}]}
I don't want to use jQuery, can somebody help me!
There is a little problem in your regex. The backslash \ means escape. So when you write \" it finds only one quotation mark, the backslash escapes it as it is a special character.
You have to escape both the backslash and the quotation mark:
str = str.replace(/\\\"/g, '\\\\"');
This will produce the wished result.
Please read the comment from the user zerkms below your question. I don't really understand what this replacing is good for. Maybe you have the so called x-y problem:
https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
EDIT:
The above posted code line want work, because of the reasons explained in the comment below from the user zerkms. There is a workaround using raw string:
String.raw`\"`.replace(/\"/g, '\\"');
This is tested and should work.
If you are fetching a path from HTML input tag and you need to replace the \ in path with \\ for further processing in code. You can use the following
var myString = $('#myID').val(); // c:\User\path
console.log(myString.split('\\').join('\\\\')); // c:\\User\\path

How to replace all occurring same character like ' with ;$39

I am using following code, in which i want to replace all ' with ;$39 but its not working fine . It's replace only first ' .
var searchUserName = document.getElementById("ctl00_ContentMain_UserSearchColl").value.replace("/\'/g", ";$39;");
For example: Ram's's .Output: Ram;$39s;$39s
Thanks in advance.
You don't need to put the regexp inside double quotes. Remove them.
value.replace(/'/g, ';$39;')
Also note that you need not "escape" the single quote. (Thanks #Paul S. for pointing)

Regex to strip BBCode

I need a regular expression to strip out any BBCode in a string. I've got the following (and an array with tags):
new RegExp('\\[' + tags[index] + '](.*?)\\[/' + tags[index] + ']');
It picks up [tag]this[/tag] just fine, but fails when using [url=http://google.com]this[/url].
What do I need to change? Thanks a lot.
I came across this thread and found it helpful to get me on the right track, but here's an ultimate one I spent two hours building (it's my first RegEx!) for JavaScript and tested to work very well for crazy nests and even incorrectly nested strings, it just works!:
string = string.replace(/\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]/img, '');
If string = "[b][color=blue][url=www.google.com]Google[/url][/color][/b]" then the new string will be "Google". Amazing.
Hope someone finds that useful, this was a top match for 'JavaScript RegEx strip BBCode' in Google ;)
You have to allow any character other than ']' after a tag until you find ' ]'.
new RegExp('\\[' + tags[index] + '[^]]*](.*?)\\[/' + tags[index] + ']');
You could simplify this to the following expression.
\[[^]]*]([^[]*)\[\\[^]]*]
The problem with that is, that it will match [WrongTag]stuff[\WrongTag], too. Matching nested tags requires using the expression multiple times.
You can check for balanced tags using a backreference:
new RegExp('\\[(' + tags.Join('|') + ')[^]]*](.*?)\\[/\\1]');
The real problem is that you cant't match arbitrary nested tags in a regular expression (that's the limit of a regular language). Some languages do allow for recursive regular expressions, but those are extensions (that technically make them non-regular, but doesn't change the name that most people use for the objects).
If you don't care about balanced tags, you can just strip out any tag you find:
new RegExp('\\[/?(?:' + tags.Join('|') + ')[^]]*]');
To strip out any BBCode, use something like:
string alltags = tags.Join("|");
RegExp stripbb = new RegExp('\\[/?(' + alltags + ')[^]]*\\]');
Replace globally with the empty string. No extra loop necessary.
I had a similar problem - in PHP not Javascript - I had to strip out BBCode [quote] tags and also the quotes within the tags. Added problem in that there is often arbitrary additional stuff inside the [quote] tag, e.g. [quote:7e3af94210="username"]
This worked for me:
$post = preg_replace('/[\r\n]+/', "\n", $post);
$post = preg_replace('/\[\s*quote.*\][^[]*\[\s*\/quote.*\]/im', '', $post);
$post = trim($post);
lines 1 and 3 are just to tidy up any extra newlines, and any that are left over as a result of the regex.
I think
new RegExp('\\[' + tags[index] + '(=[^\\]]+)?](.*?)\\[/' + tags[index] + ']');
should do it. Instead of group 1 you have to pick group 2 then.
Remember that many (most?) regex flavours by default do not let the DOT meta character match line terminators. Causing a tag like
"[foo]dsdfs
fdsfsd[/foo]"
to fail. Either enable DOTALL by adding "(?s)" to your regex, or replace the DOT meta char in your regex by the character class [\S\s].
this worked for me, for every tag name. it also supports strings like '[url="blablabla"][/url]'
str = str.replace(/\[([a-z]+)(\=[\w\d\.\,\\\/\"\'\#\,\-]*)*( *[a-z0-9]+\=.+)*\](.*?)\[\/\1\]/gi, "$4")

Categories

Resources