Replacing New Line Character - javascript

I need a little help replacing a special character in a string using a regular expression that I just can't seem to figure out.
Here is the string that I have, and the special character is a "↵". Essentially I'd like to replace every "↵" with a comma.
var string = "http://espn.com↵http://yellowpages.com↵http://reddit.com↵http://usps.com http://uber.com↵http://cnn.com↵http://w3schools.com↵http://hitch.com↵http://sdsu.com↵http://sf.com↵http://kings.com"
A little background about what I'm doing, perhaps there is an easier way to do this. I'm getting the value of a textarea where each entry (url) is typed out on a new line and trying to format it into an array of urls.
The string above is what I'm getting after getting the value of the textarea.
Thanks for any help.

If regex is not mandatory then try
string = string.split(/\n|\r|↵/).join( "," );

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 do I replace string within quotes in javascript?

I have this in a javascript/jQuery string (This string is grabbed from an html ($('#shortcode')) elements value which could be changed if user clicks some buttons)
[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="visualizer_plugin" path="map"
source_files="bundeslander_staple.csv" include cols="1,2,4" exclude cols="3"]
In a textbox (named incl_sc) I have the value:
include cols="2,4"
I want to replace include_cols="1,2,4" from the above string with the value from the textbox.
so basically:
How do I replace include_cols values here? (include_cols="2,4" instead of include_cols="1,2,4") I'm great at many things but regex is not one of them. I guess regex is the thing to use here?
I'm trying this:
var s = $('#shortcode').html();
//I want to replace include cols="1,2,4" exclude cols="3"
//with include_cols="1,2" exclude_cols="3" for example
s.replace('/([include="])[^]*?\1/g', incl_sc.val() );
but I don't get any replacement at all (the string s is same string as $("#shortcode").html(). Obviously I'm doing something really dumb. Please help :-)
In short what you will need is
s.replace(/include cols="[^"]+"/g, incl_sc.val());
There were a couple problems with your code,
To use a regex with String.prototype.replace, you must pass a regex as the first argument, but you were actually passing a string.
This is a regex literal /regex/ while this isn't '/actually a string/'
In the text you supplied in your question include_cols is written as include cols (with a space)
And your regex was formed wrong. I recomend testing them in this website, where you can also learn more if you want.
The code above will replace the part include cols="1,2,3" by whatever is in the textarea, regardless of whats between the quotes (as long it doesn't contain another quote).
First of all I think you need to remove the quotes and fix a little bit the regex.
const r = /(include_cols=\")(.*)(\")/g;
s.replace(r, `$1${incl_sc.val()}$3`)
Basically, I group the first and last part in order to include them at the end of the replacement. You can also avoid create the first and last group and put it literally in the last argument of the replace function, like this:
const r = /include_cols=\"(.*)\"/g;
s.replace(r, `include_cols="${incl_sc.val()}"`)

JavasScript Regex to exclude specific characters which are stored in a string variable, spaces, and change remaining characters to underscores

This is for a hangman-type guessing game. I already figured out how to use a Regex to display the letters as underscores on the page with appropriate spacing. Now I want use a Regex to do the following, all in one expression:
Check a string containing the correct answer this.answers[arraysIndex], against the string containing all of the user's correct guesses rightString
In the correct answer string: change only the letters that don't match the correct guesses string into underscores. This means I want to keep the spaces unchanged too.
I've tried this:
var regex = new RegExp("/(?![^"+rightString+"])/[\A-Za-z/])/","g");
newDisplay = (this.answers[arraysIndex]).replace(regex, "_");
...and this:
newDisplay = (this.answers[arraysIndex]).replace("/(?![^+rightString+])/[\A-Za-z/])/g", "_")
...and countless slight variations of each. I'm not married to the idea of using a string variable, I could use an array variable too, or maybe there's something that hasn't even occurred to me. I've researched exhaustively on here and many other resources (that's how I solved my first problem) but this one's got me beat. Any help is greatly appreciated.

Replace all URL occurrences of string by another in Node js

I am trying to replace all occurrences of http://xyz.yzx.com/abc/def/ by /qwe/ in String in Node js. I am very new to Node js. So, I think I am doing some mistake in syntax. Following is the code with which I am trying.
var newString = originalString.replace("http:\/\/xyz\.yzx\.com\/abc\/def\//g", "/qwe/");
But this is not doing any replace. Can someone suggest what I am doing wrong? I have tried lot of tweaks but somehow I am not able to achieve the replace all occurrences.
Any suggestions you can give would be really appreciated.
If a string is passed as replaces first argument it will only replace the first occurence ( which is badly implemented in my opinion). So we either use a small workaround:
var newString = originalString
.split("http:\/\/xyz\.yzx\.com\/abc\/def")
.join("/qwe/");
Or we need to remove the string literal and escape every / with a \/ ... :/
This works fine, have a look:
originalString.replace(/\http:\/\/xyz\.yzx\.com\/abc\/def\//g, '/qwe/')

Remove slashes from string using RegEx in JavaScript

I am trying to remove all special characters except punctuation from a customer complaint textarea using this code:
var tmp = complaint;
complaint = new RegExp(tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, ''));
but it keeps placing "/" in front, and in back of the string after sanitizing.
Example:
Hi, I h#ve a% probl&em wit#h (one) of your products.
Comes out like this
/Hi, I have a problem with one of your products./
I want
Hi, I have a problem with one of your products.
Thanks in advance for any help given.
The variable complaint is converted to a regular expression because you use the RegExp() constructor.
This probably isn't what you want. (I assume you want complaint to be a string).
Strings and regular expressions are two completely different data types.
Your output demonstrates how JavaScript displays regular expressions (surrounded by / characters).
If you want a string, don't create a regular expression (i.e. remove the RegExp constructor).
In other words:
complaint = complaint.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');
You don't need the RegExp constructor:
complaint = tmp.replace(/[^a-zA-Z,.!?\d\s:]/gi, '');

Categories

Resources