How to make new line from a xml response string - javascript

I get my data from an API, which return XML, I already convert it to json because I use angularjs, the field that I need, store Songs Lyrics and it used this symbol ↵ when ever it should go to new line.
for example :
You shout it loud↵But I can’t hear a word you say↵I’m talking loud, not saying much↵↵I’m criticized but all your bullets ricochet↵You shoot me down, but I get up
example above, is something that I get when I use console.log() but when I show this field to my HTML page, its just string with no ↵ in it. I don't know why it not show in HTML, and if its something to make new line, it's not happening.
I was thinking to replace ↵ with <br /> is it possible? I will be appreciate it if you guys can help me with that.
UPDATE :
I use angularjs and fill the model with lyric and show it with {{lyric}} in my html
but as you can see in picture, when I use console.log($scope.lyric) string is formated well, but when I show the same model in HTML, its like this

Simple regexr string replace should take care of it:
var str = 'You shout it loud↵But I can’t hear a word you say↵I’m talking loud, not saying much↵↵I’m criticized but all your bullets ricochet↵You shoot me down, but I get up';
var formatted = str.replace(/↵/ig, "<br/>\n");
console.log(formatted);
document.write(formatted);
The regexr finds everything that matches the character between the / signs and replaces them with a standard newline \n and a HTML breakline tag <br/>.
The i and g flags mean Case Insensitive and Search Global respectively.
Case Insensitive catches the characters even if they are in a different case. Search Global means that if you input a multi line string, then it will replace on all lines and not just on the first.

I just figure it out, I let you know how it works in case of anyone else face with same problem :
when I show lyric like this :
<p>{{lyric}}</p>
it ignored my new lines. but when I use this :
<pre>{{lyrics}}</pre>
it works!

Related

Why do I need to replace \n with \n?

I have a line of data like this:
1•#00DDDD•deeppink•1•100•true•25•100•Random\nTopics•1,2,3,0•false
in a text file.
Specifically, for my "problem", I am using Random\nTopics as a piece of text data, and I then search for '\n', and split the message up into two lines based on the placement of '\n'.
It is stored in blockObj.msg, and I search for it using blockObj.msg.split('\n'), but I kept getting an array of 1 (no splits). I thought I was doing something fundamentally wrong and spent over an hour troubleshooting, until on a whim, I tried
blockObj.msg = blockObj.msg.replace(/\\n/g, "\n")
and that seemed to solve the problem. Any ideas as to why this is needed? My solution works, but I am clueless as to why, and would like to understand better so I don't need to spend so long searching for an answer as bizarre as this.
I have a similar error when reading "text" from an input text field. If I type a '\n' in the box, the split will not find it, but using a replace works (the replace seems pointless, but apparently isn't...)
obj.msg = document.getElementById('textTextField').value.replace(/\\n/g, "\n")
Sorry if this is jumbled, long time user of reading for solutions, first time posting a question. Thank you for your time and patience!
P.S. If possible... is there a way to do the opposite? Replace a real "\n" with a fake "\n"? (I would like to have my dynamically generated data file to have a "\n" instead of a new line)
It is stored in blockObj.msg, and I search for it using blockObj.msg.split('\n'),
In a JavaScript string literal, \n is an escape sequence representing a new line, so you are splitting the data on new lines.
The data you have doesn't have new lines in it though. It has slash characters followed by n characters. They are data, not escape sequences.
Your call to replace (blockObj.msg = blockObj.msg.replace(/\\n/g, "\n")) works around this by replacing the slashes and ns with new lines.
That's an overcomplicated approach though. You can match the characters you have directly. blockObj.msg.split('\\n')
in your text file
1•#00DDDD•deeppink•1•100•true•25•100•Random\nTopics•1,2,3,0•false
means that there are characters which are \ and n thats how they are stored, but to insert a new line character by replacement, you are then searching for the \ and the n character pair.
obj.msg = document.getElementById('textTextField').value.replace(/\\n/g, "\n")
when you do the replace(/\\n/g, "\n")
you are searching for \\n this is the escaped version of the string, meaing that the replace must find all strings that are \n but to search for that you need to escape it first into \\n
EDIT
/\\n/g is the regex string..... \n is the value... so /\REGEXSTUFFHERE/g the last / is followed by regex flags, so g in /g would be global search
regex resources
test regex online

How to replace single quotation marks with "\"?

I'm building and inventory system and I'm trying to insert some data into MySql and noticed that I get errors when trying to insert things such as 1" Monitor Cable, or anything with quotation marks for that matter. Things such as part description and the part name could all potentially contain quotation marks or apostrophes.
I know that I can just put a "\" before the quotation marks or apostrophe's by using javascript's replace method, but I'm not sure what that would look like. If anyone could help me out, that would be great!
I assume that you process some sql in node.js and its parts are not directly copied from user input (this will be danger/unsafe) but first you filter input to prevent sql injection - if yes then try
let str = '1" Monitor Cable'
console.log( str.replace(/"/g,'\\"') );

How to parse out quotes from Text to work in a Javascript Confirm Message Box

I am using the below code from the post below to show a JavaScript Confirm message based on data out of the database if the NavigationUrl is a '.com' This works EXCEPT when there are " quotes in the text. Does anyone know how I can parse out the quotes or set the quotes properly so the JavaScript will display quotes in the message?
Here is the code on another post to actuall set up the onclick event on the hyper link etc:
http://forums.asp.net/p/2026622/5833708.aspx?p=True&t=635549629987458698
I've tried the following but when I click the link and it is set to contain a .com nothing happens. If I add text that has NO " quotes it works fine. The length of the text doesn't seem to matter:
C# Code when I am pulling the data from my database table:
public string GetExternalDisclaimerText()
{
string externalDisclaimerText = context.TEST_GLOBAL.Where(tg => tg.ITEM_NM == "DISCLAIMER_TEXT").FirstOrDefault().ITEM_VALUE_TXT ?? "N/A";
Debug.Write("before: ");
Debug.Write(externalDisclaimerText);
externalDisclaimerText = externalDisclaimerText.Replace("\"", "\"");
Debug.Write("after: ");
Debug.Write(externalDisclaimerText);
return externalDisclaimerText ?? "N/A";
}
Here is the text that does not work:
"I am pleased that we have been able to secure Coach Fisher as our head coach for the long term," athletic director Stan Wilcox said in a statement. "The commitment we are making to him is a reflection of the outstanding job he has done in leading our program to its current level of excellence. While we are delighted with the undefeated season this year and our upcoming appearance in the inaugural College Football Playoff, we began working on this new contract before the success of this past season was in full view. It is a great day for Florida State."
2 issues, you should construct your search with like this -
myString = myString.replace(/\"/g, '\"');
adding the "g" at the end will replace all occurrences in the string.
You may also encounter other characters that break your code so you should look for a more robust escape feature.
Here is the answer:
externalDisclaimerText = HttpUtility.JavaScriptStringEncode(externalDisclaimerText);

JavaScript + RegEx Complications- Searching Strings Not Containing SubString

I am trying to use a RegEx to search through a long string, and I am having trouble coming up with an expression. I am trying to search through some HTML for a set of tags beginning with a tag containing a certain value and ending with a different tag containing another value. The code I am currently using to attempt this is as follows:
matcher = new RegExp(".*(<[^>]+" + startText + "((?!" + endText + ").)*" + endText + ")", 'g');
data.replace(matcher, "$1");
The strangeness around the middle ( ((\\?\\!endText).)* ) is borrowed from another thread, found here, that seems to describe my problem. The issue I am facing is that the expression matches the beginning tag, but it does not find the ending tag and instead includes the remainder of the data. Also, the lookaround in the middle slowed the expression down a lot. Any suggestions as to how I can get this working?
EDIT: I understand that parsing HTML in RegEx isn't the best option (makes me feel dirty), but I'm in a time-crunch and any other alternative I can think of will take too long. It's hard to say what exactly the markup I will be parsing will look like, as I am creating it on the fly. The best I can do is to say that I am looking at a large table of data that is collected for a range of items on a range of dates. Both of these ranges can vary, and I am trying to select a certain range of dates from a single row. The approximate value of startText and endText are \\#\\#ASSET_ID\\#\\#_<YYYY_MM_DD>. The idea is to find the code that corresponds to this range of cells. (This edit could quite possibly have made this even more confusing, but I'm not sure how much more information I could really give without explaining the entire application).
EDIT: Well, this was a stupid question. Apparently, I just forgot to add .* after the last paren. Can't believe I spent so long on this! Thanks to those of you that tried to help!
First of all, why is there a .* Dot Asterisk in the beginning? If you have text like the following:
This is my Text
And you want "my Text" pulled out, you do my\sText. You don't have to do the .*.
That being said, since all you'll be matching now is what you need, you don't need the main Capture Group around "Everything". This: .*(xxx) is a huge no-no, and can almost always be replaced with this: xxx. In other words, your regex could be replaced with:
<[^>]+xxx((?!zzz).)*zzz
From there I examine what it's doing.
You are looking for an HTML opening Delimeter <. You consume it.
You consume at least one character that is NOT a Closing HTML Delimeter, but can consume many. This is important, because if your tag is <table border=2>, then you have, at minimum, so far consumed <t, if not more.
You are now looking for a StartText. If that StartText is table, you'll never find it, because you have consumed the t. So replace that + with a *.
The regex is still success if the following is NOT the closing text, but starts from the VERY END of the document, because the Asterisk is being Greedy. I suggest making it lazy by adding a ?.
When the backtracking fails, it will look for the closing text and gather it successfully.
The result of that logic:
<[^>]*xxx((?!zzz).)*?zzz
If you're going to use a dot anyway, which is okay for new Regex writers, but not suggested for seasoned, I'd go with this:
<[^>]*xxx.*?zzz
So for Javascript, your code would say:
matcher = new RegExp("<[^>]*" + startText + ".*?" + endText, 'gi');
I put the IgnoreCase "i" in there for good measure, but you may or may not want that.

How do I extract the title value from a string using Javascript regexp?

I have a string variable which I would like to extract the title value in id="resultcount" element. The output should be 2.
var str = '<table cellpadding=0 cellspacing=0 width="99%" id="addrResults"><tr></tr></table><span id="resultcount" title="2" style="display:none;">2</span><span style="font-size: 10pt">2 matching results. Please select your address to proceed, or refine your search.</span>';
I tried the following regex but it is not working:
/id=\"resultcount\" title=['\"][^'\"](+['\"][^>]*)>/
Since var str = ... is Javascript syntax, I assume you need a Javascript solution. As Peter Corlett said, you can't parse HTML using regular expressions, but if you are using jQuery you can use it to take advantage of browser own parser without effort using this:
$('#resultcount', '<div>'+str+'</div>').attr('title')
It will return undefined if resultcount is not found or it has not a title attribute.
To make sure it doesn't matter which attribute (id or title) comes first in a string, take entire html element with required id:
var tag = str.replace(/^.*(<[^<]+?id=\"resultcount\".+?\/.+?>).*$/, "$1")
Then find title from previous string:
var res = tag.replace(/^.*title=\"(\d+)\".*$/, "$1");
// res is 2
But, as people have previously mentioned it is unreliable to use RegEx for parsing html, something as trivial as different quote (single instead of double quote) or space in "wrong" place will brake it.
Please see this earlier response, entitled "You can't parse [X]HTML with regex":
RegEx match open tags except XHTML self-contained tags
Well, since no one else is jumping in on this and I'm assuming you're just looking for a value and not trying to create a parser, I'll give you what works for me with PCRE. I'm not sure how to put it into the java format for you but I think you'll be able to do that.
span id="resultcount" title="(\d+)"
The part you're looking to get is the non-passive group $1 which is the '\d+' part. It will get one or more digits between the quote marks.

Categories

Resources