Replace characters with carriage return - JavaScript - javascript

I would like to ask for help in learning how to replace a 3 different combinations of characters from a string, and replace them with a carriage return.
The character combinations are:
++~
~~+
+~\
I would like to be able to replace those combinations with a carriage return.
String example:
Capacity for the concerts is 3,645 persons with additional safety conditions.++~ Approved contractor will barricade and cone the race route.++~ Coordinate activities and schedule with the street coordinator, 608-261-9171.++~ Animals must remain in fenced area ~~+ Maintain access to Metro stops.~~+ There is no event parking in the parking lot.~~+ Event volunteers and staff will monitor the barricades during the event.~~+ Staff will review the event for compliance to the established conditions and determine what remediation (if any) is needed and/or establish considerations for future events.+~\ Event organizer/sponsor is responsible for cleanup of event area. Charges will be assessed for any staff time or resources required for clean-up.+~\
Any help with code examples would be greatly appreciated.
Thank you!
UPDATE
I have a starter function, it does the work, but I am not sure if this is an extensible solution.
function findAndReplace() {
var string = 'Addendum and/or contract providing additional event details and conditions. Capacity for the King St. concerts is 3,645 persons with additional safety conditions as per Addendum.++~ Addendum and/or contract providing additional event details and conditions on file in Madison Parks.++~ Notification: Event participants must be notified prior to the race that they must adhere to the traffic signals. They are not allowed to stop traffic during the event.++~ Organizer must notify hotels, businesses and residents along the approved bike route. Include estimated time periods when athletics will "block" access and provide day-off contact information.++~ Call the Sayle Street Garage, 608-266-4767, 1120 Sayle St, to make arrangements to pick up and return barricades required for event. There may be charges for this equipment.++~ ';
var target1 = '++~ ';
var target2 = '~~+ ';
var target3 = '+~\\ ';
var replacement = '\n';
var i = 0, length = string.length;
for (i; i < length; i++) {
string = string.replace(target1, replacement)
.replace(target2, replacement)
.replace(target3, replacement);
}
return string;
}
console.log(findAndReplace());

This simple regex will replace all occurance in the string.
/\+\+~|~~\+|\+~\\/g
You first need to escape the \ in the string so this abc+~\monkey would become this abc+~\\monkey.
Then you can use split to split the items. map to do some cleanup on the items, then join to insert your carriage return \r\n
let str = 'Capacity for the concerts is 3,645 persons with additional safety conditions.++~ Approved contractor will barricade and cone the race route.++~ Coordinate activities and schedule with the street coordinator, 608-261-9171.++~ Animals must remain in fenced area ~~+ Maintain access to Metro stops.~~+ There is no event parking in the parking lot.~~+ Event volunteers and staff will monitor the barricades during the event.~~+ Staff will review the event for compliance to the established conditions and determine what remediation (if any) is needed and/or establish considerations for future events.+~\\ Event organizer/sponsor is responsible for cleanup of event area. Charges will be assessed for any staff time or resources required for clean-up.+~\\'
str = str.split(/\+\+~|~~\+|\+~\\/g).map(i => i.trim()).join('\r\n')
console.log(str)

You may try to use the replace function in js:-
let sampleStr = `Capacity for the concerts is 3,645 persons with additional safety conditions.++~ Approved contractor will barricade and cone the race route.++~ Coordinate activities and schedule with the street coordinator, 608-261-9171.++~ Animals must remain in fenced area ~~+ Maintain access to Metro stops.~~+ There is no event parking in the parking lot.~~+ Event volunteers and staff will monitor the barricades during the event.~~+ Staff will review the event for compliance to the established conditions and determine what remediation (if any) is needed and/or establish considerations for future events.+~\ Event organizer/sponsor is responsible for cleanup of event area. Charges will be assessed for any staff time or resources required for clean-up.+~\ `;
let replacedString = sampleStr.replace(/\++~/g, '\r').replace(/~~\+/g,'\r').replace(/\+~\\/g,'\r');
alert(replacedString);

You can try this
const str = "Capacity for the concerts is 3,645 persons with additional safety conditions.++~ Approved contractor will barricade and cone the race route.++~ Coordinate activities and schedule with the street coordinator, 608-261-9171.++~ Animals must remain in fenced area ~~+ Maintain access to Metro stops.~~+ There is no event parking in the parking lot.~~+ Event volunteers and staff will monitor the barricades during the event.~~+ Staff will review the event for compliance to the established conditions and determine what remediation (if any) is needed and/or establish considerations for future events.+~\\ Event organizer/sponsor is responsible for cleanup of event area. Charges will be assessed for any staff time or resources required for clean-up.+~\\ ";
console.log(str.replace(/\+\+~|~~\+|\+~\\/g, '<new symbol>'));

Related

React-Native Accumulate results from a loop to a single string

I want to extract the data in between the tag and, based on the content, return <View><Text>This is a Text</Text></View> or <View><Text>This is a Picture</Text></View>
The problem is that I don't know how to accumulate the result from the matches to Article, and then return {Article} as the final result.
In the case below, I should end up with that render:
<View><Text>This is a Text</Text></View>
<View><Text>This is a Picture</Text></View>
<View><Text>This is a Text</Text></View>
instead, I get the final result. I tried Article = Article + <View><Text>This is a Text</Text></View> and Article += <View><Text>This is a Text</Text></View> but they both failed.
export default class App extends React.Component {
render() {
let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str = '<RNVW><p>Markets are mixed in Asia, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted in the last quarter</em></p><p>BANGKOK -- Markets were mixed in Asia on Monday, with Japan\'s benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China\'s shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts. </p><p>The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney\'s S&P ASX/200 edged 1% lower to 7,125.10.</p></RNVW><RNVW><img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/04/1493235373large_react_apps_A-01.png"></RNVW><RNVW><p>Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks. </p><p>The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel. </p><p>"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs," Evans-Pritchard said in a commentary. </p><p>Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China\'s report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.</p></RNVW>';
let match;
let Article;
while ((match = pattern.exec(str)) !== null) {
if (match[1].startsWith("<p>") !== false) {
Article = (
<View><Text>This is a Text</Text></View>
);
} else {
Article = (
<View><Text>This is a Picture</Text></View>
);
}
}
return (
<View style={styles.container}>
{Article}
</View>
);
}
}
Hey Vincent
you were doing one mistake with Article, you are trying to allocate a new item to Article every time instead, you should go with array and push new items every time in the array.
Made some changes in your code:
class App extends Component {
articleView = () => {
let pattern = /<RNVW>(.*?)<\/RNVW>/g;
let str ="<RNVW><p>Markets are mixed in Asia, with Japan's benchmark slipping 0.7% after the government reported the economy contracted in the last quarter</em></p><p>BANGKOK -- Markets were mixed in Asia on Monday, with Japan's benchmark slipping 0.7% after the government reported the economy contracted 6.3% in annual terms in the last quarter. China's shares got a boost after the central bank stepped in to help the economy with a rate cut, extra buying of securities and tax cuts. </p><p>The Nikkei 225 in Tokyo closed at 23,523.24, while Sydney's S&P ASX/200 edged 1% lower to 7,125.10.</p></RNVW><RNVW><img src=\"https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/04/1493235373large_react_apps_A-01.png\"></RNVW><RNVW><p>Such moves will likely be followed by still more, said Julian Evans-Pritchard, given that many of the companies worst affected by the virus outbreak are smaller ones that lack access to loans from major state-run banks. </p><p>The government has also announced plans for tax cuts and other measures to help companies struggling with shut-downs of cities and plunging consumer spending and travel. </p><p>\"We think the PBOC will need to expand its re-lending quotas and relax constraints on shadow banking in order to direct more credit to struggling SMEs,\" Evans-Pritchard said in a commentary. </p><p>Wall Street closed out a wobbly day of trading Friday with the major stock indexes notching their second straight weekly gain. Though trading was mostly subdued and cautious following China's report Thursday of a surge in cases of a new virus that raised fresh concerns about global economic growth.</p></RNVW>";
let match;
let Article = [];
while ((match = pattern.exec(str)) !== null) {
if (match[1].startsWith("<p>") !== false) {
Article.push(
<View>
<Text>This is a Text</Text>
</View>
);
} else {
Article.push(
<View>
<Text>This is a Picture</Text>
</View>
);
}
}
return Article;
};
render() {
return (
<View>
{this.articleView()}
</View>
);
}
}
it will give you desired output :)
I hope that's what you were looking for!
Thanks!

Microsoft Translate Voice limit 200-400 words when request

I have a URL of Microsoft Translate Voice to get voice look like:
<audio controls autoplay>
<source src="https://www.bing.com/tspeak?&format=audio%2Fmp3&language=en&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2&text=I’m Often at the End of My Rope as a Mom of Two" type="audio/mpeg">
</audio>
The problem is: text="any text here". Any text here is limit about 200-400 word. I don't know the reason at here. In Bing Translate I can insert full 5000 words and click button audio to hear.
Have any method to pass this problem? Microsoft is limit in this URL?
Have any method to insert 5000 words like Microsoft Translate homepage?
If you open your developer console on Bing's website and start playing the sound, you'll see it sends a first mp3 request with only a couple of words, and when it's done reading it, it sends another one, and so on.
You could do the same:
// When the DOM (basically the HTML) is loaded
document.addEventListener('DOMContentLoaded', function(){
// Define your DOM elements
var getAudioBtn = document.getElementById('getAudioBtn'),
langSelect = document.getElementById("langSelect"),
langSource = document.getElementById("langSource"),
audioEl = document.getElementById('audioEl');
// Setup an event listener on the button
getAudioBtn.addEventListener('click', getContentTranslate);
// Setup an listener on the audio onended event
audioEl.addEventListener('ended', readChunkQueue);
var chunkQueue = [], // Queue of chunks of text to read
wordsPerChunk = 80, // Words per chunk
language = 'en'; // Default language
function getContentTranslate() {
// Store the language
language = langSelect.value;
// Empty the chunks array
chunkQueue = [];
// Split the text into words
var words = langSource.value.split(/ /g),
tmp = []; // Temporary array for creating a chunk
while(words.length) {
// If out temporary chunk is full, add it to the list
if (tmp.length === wordsPerChunk) {
chunkQueue.push(tmp.join(' '));
tmp = [];
}
tmp.push(words.shift());
}
if (tmp.length) {
chunkQueue.push(tmp.join(' '));
}
// Start reading these chunks
readChunkQueue();
}
function readChunkQueue() {
// If the list is empty, stop
if (!chunkQueue.length) {
return;
}
// Get the first chunk in the list
var chunk = chunkQueue.shift(),
url = 'https://www.bing.com/tspeak?&format=audio%2Fmp3'
+ '&language=' + encodeURIComponent(language)
+ '&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2'
+ '&text=' + encodeURIComponent(chunk);
// Set the URL as source for the audio element
audioEl.setAttribute('src', url);
}
});
<select id="langSelect">
<option value="en">English</option>
<option value="vi">Vietnamese</option>
</select>
<br>
<textarea id="langSource" placeholder="Enter text or webpage URL here">Obama Inaugural Address. 20th January 2009. My fellow citizens: I stand here today humbled by the task before us, grateful for the trust you have bestowed, mindful of the sacrifices borne by our ancestors. I thank President Bush for his service to our nation, as well as the generosity and cooperation he has shown throughout this transition. Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents. So it has been. So it must be with this generation of Americans. That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet. These are the indicators of crisis, subject to data and statistics. Less measurable but no less profound is a sapping of confidence across our land - a nagging fear that America's decline is inevitable, and that the next generation must lower its sights. Today I say to you that the challenges we face are real. They are serious and they are many. They will not be met easily or in a short span of time. But know this, America - they will be met. On this day, we gather because we have chosen hope over fear, unity of purpose over conflict and discord. On this day, we come to proclaim an end to the petty grievances and false promises, the recriminations and worn out dogmas, that for far too long have strangled our politics. We remain a young nation, but in the words of Scripture, the time has come to set aside childish things. The time has come to reaffirm our enduring spirit; to choose our better history; to carry forward that precious gift, that noble idea, passed on from generation to generation: the God-given promise that all are equal, all are free, and all deserve a chance to pursue their full measure of happiness. In reaffirming the greatness of our nation, we understand that greatness is never a given. It must be earned. Our journey has never been one of short-cuts or settling for less. It has not been the path for the faint-hearted - for those who prefer leisure over work, or seek only the pleasures of riches and fame. Rather, it has been the risk-takers, the doers, the makers of things - some celebrated but more often men and women obscure in their labor, who have carried us up the long, rugged path towards prosperity and freedom.</textarea>
<br>
<button id="getAudioBtn">GET AUDIO</button>
<br>
<audio id="audioEl" autoplay controls></audio>

Show more/less based on number of lines instead of text length

I have the show more/less done but it's based on the length of the text. What happens is, as there are characters that take more space than others, the "show more/less" words show in different places, not always at the end of the line. Sometimes I get something like this:
With the rest of the line free.
I want to check this based on the actual number of lines instead of the text length.
Here's a codePen of what I've got and below a code snippet:
$(document).ready(function() {
function splitText(text) {
var textBreak = textLimit;
var first = text.substring(0, textBreak);
var second = text.substring(textBreak);
var aux = second.substring(0, second.indexOf(" "));
var spaceIndex = second.indexOf(" ");
second = " " + second.substring(spaceIndex + 1);
first = first.substring(0, textBreak) + aux;
var bothTextes = [first, second];
return bothTextes;
}
var textLimit = 400;
var text = $("#companyDetails").html();
if (text.length > textLimit) {
var textArray = splitText(text);
$("#companyDetails").text(textArray[0]);
$("#companyDetails").append("<span onclick=\"expandText()\" class='show-more'>...<span class=\"red\">show more</span></span>");
$("#companyDetails").append("<span style=\"display: none\" class='rest-of-description'>" + textArray[1] + "</span>");
$("#companyDetails").append("<span onclick=\"collapseText()\" style=\"display: none\" class='red show-less'> show less </span>");
} else {
$("#companyDetails").text(text);
}
});
function expandText() {
$(".rest-of-description").show();
$(".show-less").show();
$(".show-more").hide();
}
function collapseText() {
$(".rest-of-description").hide();
$(".show-less").hide();
$(".show-more").show();
}
#companyDetails {
border: 1px solid red
}
.red {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="companyDetails">
We at ACME offer the services to cater for all your stuff needs. As part of the ACME Inc. network we utilise 10000000 years experience of market leading in nice services. In 2015, ACME was acquired by the ACME Group, a division of Associated ACME Ltd. By
joining forces it gives us access to extensive new resources allowing us to succeed further in attracting the highest calibre of cartoon stuff. Being a specialist site with a full range of positions across the world, ACME provides our guys with a
choice that enables us to attract the best in the industry. Our dedicated team are here to make sure we continue to provide the best service to you every time. Whether you're looking to catch roadrunner or simply to have a foldable airplane that you
can fit into your pocket after flying, ACME is the company you are looking for. I case you didn't read, here it is again: We at ACME offer the services to cater for all your stuff needs. As part of the ACME Inc. network we utilise 10000000 years experience of market leading in nice services. In 2015, ACME was acquired by the ACME Group, a division of Associated ACME Ltd. By
joining forces it gives us access to extensive new resources allowing us to succeed further in attracting the highest calibre of cartoon stuff. Being a specialist site with a full range of positions across the world, ACME provides our guys with a
choice that enables us to attract the best in the industry. Our dedicated team are here to make sure we continue to provide the best service to you every time. Whether you're looking to catch roadrunner or simply to have a foldable airplane that you
can fit into your pocket after flying, ACME is the company you are looking for.
</div>
EDIT
So after #TomHood's suggestion, I can now have the line count. However, I still need to know where am I going to break the text. I can't get the final word of a specific line...
You can do this by restricting the max-height in css, based on the line-height:
#companyDetails {
border: 1px solid red;
line-height: 1.2em;
max-height: 4.8em; //4.8 = 4 lines
overflow: hidden;
}
then you just need to change the max-height property in javascript/jQuery
$('#showMore').click(function(){
$('#companyDetails').css('max-height', 'none');
});
http://codepen.io/anon/pen/KVGpwd
You could use the following markup:
<div class="companyDetailsWrap">
<p class="companyDetailsText">We at ACME offer the services to cater for all your stuff needs. As part of the ACME Inc. network we utilise 10000000 years experience of market leading in nice services. In 2015, ACME was acquired by the ACME Group, a division of Associated ACME Ltd. By
joining forces it gives us access to extensive new resources allowing us to succeed further in attracting the highest calibre of cartoon stuff. Being a specialist site with a full range of positions across the world, ACME provides our guys with a
choice that enables us to attract the best in the industry. Our dedicated team are here to make sure we continue to provide the best service to you every time. Whether you're looking to catch roadrunner or simply to have a foldable airplane that you
can fit into your pocket after flying, ACME is the company you are looking for. I case you didn't read, here it is again: We at ACME offer the services to cater for all your stuff needs. As part of the ACME Inc. network we utilise 10000000 years experience of market leading in nice services. In 2015, ACME was acquired by the ACME Group, a division of Associated ACME Ltd. By
joining forces it gives us access to extensive new resources allowing us to succeed further in attracting the highest calibre of cartoon stuff. Being a specialist site with a full range of positions across the world, ACME provides our guys with a
choice that enables us to attract the best in the industry. Our dedicated team are here to make sure we continue to provide the best service to you every time. Whether you're looking to catch roadrunner or simply to have a foldable airplane that you
can fit into your pocket after flying, ACME is the company you are looking for.</p>
</div>
Then use this script:
$(function () {
var initial = $('.companyDetailsText').text();
$('.companyDetailsText').text(initial);
while($('.companyDetailsText').outerHeight() > $('.companyDetailsWrap').height()) {
$('.companyDetailsText').text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
$(window).resize(function() {
$('.companyDetailsText').text(initial);
while($('.companyDetailsText').outerHeight() > $('.companyDetailsWrap').height()) {
$('.companyDetailsText').text(function(index, text) {
return text.replace(/\W*\s(\S)*$/, '...');
});
}
});
});
This is basically listening to see if the height of your text exceeds the container, rather than using character count. You will just need to set your desired height in css on .companyDetailsWrap.

Javascript regular expression matches some strings, but fails on other seemingly identical strings

JSFiddle
I am using Facebook's API to pull in daily crime reports from my county's police department page. They follow a mostly standardized format, with the following patterns being what I'm going off of, and a few annoying inconsistencies:
The header is between 3-4 lines followed by two new line characters \n\n (The code cuts this out and is not part of the output below)
Different categories of crimes committed are grouped together with the first line being a capitalized string describing the types of crimes. Each category is separated by two new line characters \n\n above it.
Actual crimes committed follow the category title described above, each (most of the time) separated by one new line character \n
As an "artifact" of whatever they are copying and pasting from, a few times there are various unicode characters substituting the hyphen, including \u2013, \u2014 and \u2015
All crimes reported start with the string "BEAT", or on rare occasion "Beat"
The problem that I am running into is that sometimes the code below catches a category title detailed in #2 above, yet in other posts, the (seemingly) exact same string and circumstances doesn't catch. The angular code I'm using in a service can be seen below
me.parsePosts = function() {
var posts = facebookService.getRandomPosts(); // Just a method to return 5 random reports for now
angular.forEach(posts, function(post) {
// Some reports are incorrectly double spaced and inconsistent
// with spacing and capitalization
var fixedPost = post.message
.replace(/^Beat/, 'BEAT') // They were a little inconsistent back in the day
.replace('\n\n###', '') // All posts end with a useless ###
.replace('\u2013', '-') // Pesky unicode characters!
.replace('\u2014', '-')
.replace('\u2015', '-')
.replace('\n\nARRESTED', '\nARRESTED') // would help if this was consistent
.replace(/(?:\\[rn ]|[\r\n ]+)BEAT/gi, '\nBEAT'), // same with the reports...
postSplit = fixedPost.split('\n\n'), // split up the post into potential categories
header = postSplit.splice(0,1); // I don't want the standard header of the post
// Pass in postSplit .join()'d back together for debugging
me.getCategoriesFromPost(postSplit, postSplit.join('\n\n'));
});
};
me.getCategoriesFromPost = function(postArray, post) {
var categoryRegexp = /[A-Z\-&\/: ]+$/,
categories = [], uniqCategories = [];
angular.forEach(postArray, function(a) {
var split = a.split('\n'), // Extract the category from the list of crimes
potentialCategory = split[0].trim(); // There's often an unwanted trailing space
if (potentialCategory.match(categoryRegexp)) {
categories.push(potentialCategory);
}
});
// Every blue moon they repost a category twice, I just want one
// and I'll merge the two together afterwards
uniqCategories = categories.filter(function(a,b) {
return categories.indexOf(a) == b;
});
console.log(uniqCategories); // log off all the categories in the post
console.log(post); // Display the actual post so i can visibly verify it all worked
};
So as an example, in one post:
console.log(uniqCategories); (original raw text as received from facebookService.getRandomPosts()):
BURGLARY COMMERCIAL
BEAT E1 SPRINT WIRELESS, 7300 ASSATEAGUE DR, 3/19 0426: Unknown suspect(s) gained entry to the business by breaking the glass door. The suspect(s) stole electronics. 14-25638
BEAT D6 MONTPELIER LIQUORS, 7500 MONTPELIER RD, 3/19 0513: Unknown suspect(s) gained entry to the business by breaking the glass door. The suspect(s) stole liquor, lottery tickets, and an ATM machine. 14-25641
BEAT D4 MACY’S, 10300 LITTLE PATUXENT PKWY, 3/19 0501: Two unknown male suspects, wearing masks, gained entry to the business by breaking the glass door. The suspects were interrupted by a store employee and fled without taking anything. 14-25642
SUSPECT VEHICLE: black Dodge pickup
BURGLARY NON COMMERCIAL
BEAT B3 6600 ASPERN DR, 3/17 2354: Four suspects gained entry to the residence via unknown means. No sign of forced entry. 14-25220
ARRESTED:
Karlin Lamont Harris, 23, of Pirch Way in Elkridge, charged with fourth-degree burglary
Steven Lee Hubbard, 29, of Edgewater, charged with fourth-degree burglary
Jessie Tyler Holt, 22, of Pine Tree Rd in Jessup, charged with fourth-degree burglary
Brittney Victoria McEnaney, 26, of Pasadena, charged with fourth-degree burglary
BEAT C1 6900 BENDBOUGH CT, 3/18 1400: Unknown suspect(s) gained entry to the residence via the front door. No sign of forced entry. The suspect(s) stole jewelry. 14-25392
BEAT B4 7100 DEEP FALLS WAY, 3/18 1100-1440: Unknown suspect(s) gained entry to the residence by forcing a rear basement window. The suspect(s) stole jewelry and electronics. 14-25404
VEHICLE THEFT & ATTEMPTS
BEAT E2 7-11, 9600 WASHINGTON BLVD, 3/18 0409:
05 Acura Tag 1AV8629 14-25277 (Keys left in vehicle.)
And console.log(post); returns
["BURGLARY COMMERCIAL", "BURGLARY NON COMMERCIAL", "VEHICLE THEFT & ATTEMPTS"]
Yet on another post, console.log(uniqCategories); (original raw text as received from facebookService.getRandomPosts()):
ROBBERY COMMERCIAL
BEAT B3 ZIPS DRY CLEANING, 6500 OLD WATERLOO RD, 3/22 1900: An unknown suspect entered the business through an unlocked rear door. The suspect threatened an employee and demanded cash. The employee complied. The suspect fled the business. 14-26959
SUSPECT: B/M, 5’8-5’9, black hoodie and pants, backpack
ROBBERY NON COMMERCIAL
BEAT E7 7-11 PARKING LOT, 9100 MAIER RD, 03/23 1632: Suspect stole cash from an acquaintance and caused an abrasion with an unknown sharp object. Police are investigation the possibility it may be drug related. 14-27243
SUSPECT: B/M, 5’8, 200 lbs, dreadlocks
BURGLARY COMMERCIAL
BEAT E1 MEGATELECOM, 8600 WASHINGTON BLVD #106, 3/22 0933: Unknown suspect(s) gained entry to the business by breaking a window. The suspect(s) stole electronics. 14-26793
BEAT F3 CATTAIL CREEK COUNTRY CLUB, 3600 CATTAIL CREEK DR, 03/22 1600- 03/23 0630: Unknown suspect(s) gained entry to a garage through an unlocked door. The suspect(s) stole golf carts. 14-27127
BURGLARY NON COMMERCIAL
BEAT E2 9300 BREAMORE CT, 03/21 1210 ATTEMPT: Two suspects attempted to gain entry via a rear slider. The resident yelled and the suspects fled, but were later caught by police. 14-26458
ARRESTED:
Travis Donte Mackell, 23, of Baltimore, charged with fourth-degree burglary
Maurice Debuiel Aye, 26, of Baltimore, charged with fourth-degree burglary
BEAT D3 5500 COLUMBIA RD, 3/21: An unknown suspect gained entry to the residence through an unlocked rear slider. The suspect woke the resident, who ultimately got the suspect to leave. It appears he may have entered the wrong residence. 14-26712
SUSPECT: B/M, 5’8, 200 lbs
BEAT B4 7500 HEARTHSIDE WAY, 3/22 1700- 1800: Three unknown black male suspects stole a bicycle, which was unsecured on a bike rack. 14-27185
BEAT E3 9100 BRYANT AVE, 3/23 2213: Unknown suspects gained entry to the residence by prying open the kitchen window. Nothing appeared to be taken. 14-27308
BEAT B3 8000 KEETON RD, 3/23 1930- 2230: Unknown suspect(s) gained entry to the residence through an unlocked window. The suspect(s) stole a computer and jewelry. 14-27314
BEAT A3 9000 FREDERICK RD, 3/23 0205: The suspect kicked in an acquaintance’s door after a verbal altercation and assaulted him. 14-27361
ARRESTED: Michael Wilson Sittig, 34, of Frederick Road in Ellicott City, charged with second-degree assault, third- and fourth-degree burglary, malicious destruction of property, and disorderly conduct
VEHICLE THEFT & ATTEMPTS
BEAT D2 5100 ELIOTS OAK DR, 03/22 2130- 3/23 0700:
12 Hyundai Sonata Red MD 5AN2945 14-27135
and console.log(post) only returns:
["ROBBERY COMMERCIAL", "VEHICLE THEFT & ATTEMPTS"]
I expect it to return ["ROBBERY COMMERCIAL", "ROBBERY NON COMMERCIAL", "BURGLARY COMMERCIAL", "BURGLARY NON COMMERCIAL", "VEHICLE THEFT & ATTEMPTS"]
In that instance, it's clear that my code matches the former instances of BURGLARY COMMERCIAL and BURGLARY NON COMMERCIAL, but not the latter. What gives? Also, feel free to correct me and tell me I'm doing it all wrong with the wall of .replace(), and that there's a better way to do it, if there is. Thanks a bunch for the help!
String.replace replaces the FIRST occurrence. You need to change all your String.replace with a regex to replace all occurrences. Something like this (although I'm not sure how the unicode chars work in regex):
post.message
.replace(/^Beat/ig, 'BEAT') // They were a little inconsistent back in the day
.replace('/\n\n###/g', '') // All posts end with a useless ###
.replace('/\u2013/g', '-') // Pesky unicode characters!
.replace('/\u2014/g', '-')
.replace('/\u2015/g', '-')
.replace('/\n\nARRESTED/g', '\nARRESTED') // would help if this was consistent
.replace(/(?:\\[rn ]|[\r\n ]+)BEAT/gi, '\nBEAT'), // same with the reports...
You were missing a few more delimiter replacements before your split. Namely, I added:
post.message
...
.replace( /\s*\n\s\n/g, '\n\n')
.replace(/\s BEAT/g, 'BEAT') ...
See updated fiddle
TL;DR; (updated based on comments)
If you look at the messages after the original replace(...) function calls, and before the .split('\n\n'), some of them have a blank space at the very end followed by a newline, then another blank, and newline.
None of your original replace() took care of that. Also, some only had a newline, blank, newline pattern (& why the first space in the regex has a *). Then, some of the BEAT keywords in the message were preceded by one or more blanks so we are removing those to ensure that BEAT is always preceded by a newline.
If you un-comment out the logging lines in the fiddle and comment out the fix, you will see the array of elements at each step.
In one of those, you will see that one array element contains not only what we expect (one report) but the next category is embedded there as well (which is why you would see fewer).
Then I just tried to see what was different about those line endings and checking if the replace() functions took care of them before the split(...) call...
Let me know if you want me to explain it better.

how to user Javascript regex - split string without losing data and format the paragraph

i have the following paragraph. Now i want to manage the string in the following and i want to break the line if (1), (2) such condition occur or a specific string Exception will occur.
The requirements of this chapter apply to the following: (1) New
buildings or portions thereof used as health care occupancies (see
1.4.1) (2) Additions made to, or used as, a health care occupancy (see 4.6.6 and 18.1.1.4) Exception: The requirement of 18.1.1.1.1 shall not apply to additions classified as occupancies other than health care
that are separated from the health care occupancy in accordance with
18.1.2.1 and conform to the requirements for the specific occupancy in accordance with Chapters 12 through 17 and Chapters 20 through 42, as
appropriate.(3) Alterations, modernizations, or renovations of
existing health care occupancies (see 4.6.7 and 18.1.1.4) (4) Existing
buildings or portions thereof upon change of occupancy to a health
care occupancy (see 4.6.11) Exception*: Facilities where the authority
having jurisdiction has determined equivalent safety has been provided
in accordance with Section 1.5.
In the following way:-
The requirements of this chapter apply to the following:
(1) New buildings or portions thereof used as health care occupancies
(see 1.4.1)
(2) Additions made to, or used as, a health care occupancy (see 4.6.6
and 18.1.1.4)
Exception: The requirement of 18.1.1.1.1 shall not apply to additions
classified as occupancies other than health care that are separated
from the health care occupancy in accordance with 18.1.2.1 and conform
to the requirements for the specific occupancy in accordance with
Chapters 12 through 17 and Chapters 20 through 42, as appropriate.
(3) Alterations, modernizations, or renovations of existing health
care occupancies (see 4.6.7 and 18.1.1.4)
(4) Existing buildings or portions thereof upon change of occupancy
to a health care occupancy (see 4.6.11) Exception*: Facilities where
the authority having jurisdiction has determined equivalent safety has
been provided in accordance with Section 1.5.
Thank you
var str = '(1)point 1 (2) point2 exception: some exception (3) point 3'
str = str.replace(/(\(\d+\)|exception\s*\:)/gi, "<br />$1");

Categories