How to remove special characters from string using javascript - javascript

When # comes in string, I want to split it on new line using JavaScript.
Please help me.
Sample input:
This application helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#
Expected output:
This helps the user to instantiate
Removed
Basic
afdaf
Clip
Python
matching of many parts

you can simply replace '#' by '\n'
var mainVar = 'This application helps the user to instantiate#Removed#Basic#afdaf#Clip#Python#matching';
console.log(mainVar.replace(/[^\w\s]/gi, '\n'));

Convert a string into array and loop through the array and print values one by one.
var str = "helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#";
str.split("#").forEach(function(entry) {
console.log(entry);
});

You can try this:
You should use the string replace function, with a single regex. Assuming by special characters
var str = "This application helps the user to instantiate #Removed#Basic#afdaf#Clip#Python#matching of many parts#";
console.log(str.replace(/[^a-zA-Z ]/g, "\n"));

The below solution will split based on the # and store it in an array.
This solution will come in handy with splitting strings.
var sentence = '#Removed#Basic#afdaf#Clip#Python#matching of many parts#'
var newSentence = [];
for(var char of sentence.split("#")){
console.log(char); // This will print each string on a new line
newSentence.push(char);
}
console.log(newSentence.join(" "));

Related

Insert few characters before character in a string variable (javascript)

I have this following javascript variable.
var data = "ashley, andy, juana"
i Want the above data to look like this.
var data = "Sports_ashley, Sports_andy, Sports_juana"
It should be dynamic in nature. any number of commas can be present in this variable.
Can someone let me an easy way to achieve this please.
Using .replace should work to add sports before each comma. Below I have included an example.
var data = data.replace(/,/g , ", Sports_");
In that example using RegExp with g flag will replace all commas with Sports, instead of just the first occurrence.
Then at the end you should just be able to append Sports to the end like so.
data = "Sports_" + data;
Probably an overkill, but here is a generic solution
function sportify(data) {
return data
.split(/\s*,\s*/g) //splits the string on any coma and also takes out the surrounding spaces
.map(function(name) { return "Sports_" + name } ) //each name chunk gets "Sport_" prepended to the end
.join(", "); //combine them back together
}
console.log(sportify("ashley, andy, juana"));
console.log(sportify("ashley , andy, juana"));
String.replace()
Array.map()
Array.join()
EDIT: updated with the new version of the OP
Use a regex to replace all occurrences of a , or the beginning of the string using String#replace()
var input = "ashley, andy, juana"
var output = input.replace(/^|,\s*/g, "$&Sports_");
console.log(output);

Extract substrings from a string with a certain character

I'm trying to extract all substrings that start with ! for a string in Javascript. for example if my string is:
Hi Jack !Smile, This is a !silly text to try out this !Code!
So the output should be an array with elements:
var arr = ['Smile', 'Silly', 'Code']
The reason I'm doing is because I want to convert these codes into emoticons for my chatroom and "!" is an indicator that this is an emoticon code. Is there any fast and optimal to do this and not go through every word using a for loop?
I think a simple regex along with an array processing should do it
var string = "Hi Jack !Smile, This is a !silly text to try out this !Code!";
var match = string.match(/!(.+?)\b/g),
array = match ? match.map(function(val) {
return val.substring(1)
}) : [];
snippet.log(JSON.stringify(array))
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can use the following regex
!(.+?)\b

regex replace not replacing (google apps script)

I am writing a google apps script that pulls the content from a CSV file in a gmail attachment. I need to split the csv data into several an array (with each row being it's own array). I've got all that down.
My problem is this: One of the values in the CSV is a "City, St" format. So when I split the array using string.split(',') I end up with an extra "column." My idea to fix this was to back up and kill that comma in the initial string. Here's the relevant portion of my code:
var attachments = msgs[i][j].getAttachments();
for (var k = 0; k < attachments.length; k++) {
var attachmentData = attachments[k].getDataAsString();
var regex = new RegExp('\,\s(?:[A-Z]{2}\")', 'gi');
attachmentData.replace(regex,' ');
...
So what I'm trying to do is just find a comma, followed by a space, followed by exactly two letters, then a quotation mark. I want to just replace the comma with a space. I've also tried
var regex = new RegExp('(\,\s)([A-Z]{2}\")', 'gi');
attachmentData.replace(regex,$2);
with no luck. Here's a random sample of the (very long) data string I'm running this on:
Voice,Incoming,(###) ###-####,(###) ###-####,,,,"Dallas, TX",12/12/2014,06:26 PM,Phone Call,Voicemail,00:00:27,$0.000,-,,
,Incoming,(###) ###-####,,###,,,"Dallas, TX",12/12/2014,06:26 PM,Phone Call,Voicemail,00:00
Can anyone see what I'm not seeing as to why this isn't working? (Or have any ideas of a better way to do this?)
The replace() method returns a new string with some or all matches
of a pattern replaced by a replacement.
The str.replace does not change the string, where as returns a new string with the replace. Hence you may want to write something like
var regex = new RegExp('(,\\s)([A-Z]{2}")', 'gi');
var replacedData = attachmentData.replace(regex,'$2');
Note
You can drop the first capture group as
var regex = new RegExp(',\\s([A-Z]{2}")', 'gi');
var replacedData = attachmentData.replace(regex,'$1');
You can make use of a regex with this condition and then print back the block with $1 together with the space:
s = s.replace(/,( [A-Z]{2}")/, ' $1');
^^ ^ ^^^
comma ^^^^^^^^^ print back replacing comma with space
|
catch the group of space + two letters + "
See it live:
var s = 'Voice,Incoming,(###) ###-####,(###) ###-####,,,,"Dallas, TX",12/12/2014,06:26 PM,Phone Call,Voicemail,00:00:27,$0.000,-,, ,Incoming,(###) ###-####,,###,,,"Dallas, TX",12/12/2014,06:26 PM,Phone Call,Voicemail,00:00';
s = s.replace(/,( [A-Z]{2})/, ' $1');
document.write(s)

Regex .exec into array

I want to capture some values in a string, THEN return them to the page. Here is an example of the code. As I understand, the .exec should store the values it matches into the array correct? This should return Savage, Betsy. Can someone enlighten me on to what's wrong?
var regex = /\b(Betsy)(Savage)\b/i;
var string = "My friend is Betsy Ann Savage";
var arrayMatch = null;
while(arrayMatch = regex.exec(string)){
document.getElementById("text").innerHTML = arrayMatch[1] + ", " + arrayMatch[0];
}
You don't get any matches like this. You could add .* between (Betsy) and (Savage)...
It sounds like you think \b(Besty)(Savage)\b will match EITHER Besty, OR Savage, but that isn't the case. It's looking for one string where both parts are combined - you might as well try to match \b(BetsySavage)\b. This is because a while yes, you do have two groups separated by parentasis, you have them directly next to each other, so the Regex engine says, 'okay', I'll look for both right next to each other. I think what you really want to do is use | which represents an OR. As in \b(Besty|Savage)\b.

Parse string regex for known keys but leave separator

Ok, So I hit a little bit of a snag trying to make a regex.
Essentially, I want a string like:
error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z
to be parsed to read
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
ateTo=2013-01-16T05:00:00.000Z
So I want it to pull known keywords, and ignore other strings that have =.
My current regex looks like this:
(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=[\w\s\f\-\:]+(?![(error|user|dateFrom|dateTo|timeFrom|timeTo|hang)\=])
So I'm using known keywords to be used dynamically so I can list them as being know.
How could I write it to include this requirement?
You could use a replace like so:
var input = "error=some=new item user=max dateFrom=2013-01-15T05:00:00.000Z dateTo=2013-01-16T05:00:00.000Z";
var result = input.replace(/\s*\b((?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/g, "\n$1");
result = result.replace(/^\r?\n/, ""); // remove the first line
Result:
error=some=new item
user=max
dateFrom=2013-01-15T05:00:00.000Z
dateTo=2013-01-16T05:00:00.000Z
Another way to tokenize the string:
var tokens = inputString.split(/ (?=[^= ]+=)/);
The regex looks for space that is succeeded by (a non-space-non-equal-sign sequence that ends with a =), and split at those spaces.
Result:
["error=some=new item", "user=max", "dateFrom=2013-01-15T05:00:00.000Z", "dateTo=2013-01-16T05:00:00.000Z"]
Using the technique above and adapt your regex from your question:
var tokens = inputString.split(/(?=\b(?:error|user|dateFrom|dateTo|timeFrom|timeTo|hang)=)/);
This will correctly split the input pointed out by Qtax mentioned in the comment: "error=user=max foo=bar"
["error=", "user=max foo=bar"]

Categories