How can I ltrim and rtrim select characters in Javascript? - javascript

So I am trying to figure out how I can remove a select set of characters on the end of a string. I've tried some general 'solutions' like str.replace or creating a rtrim, but I kept seeing some situation in which it wouldn't work.
Possible inputs might be:
\r\n some random text \r\n
\r\n some random text
some random text \r\n
some random text
Only the first and the third line should be affected by this function.
Basicly I'm looking for a rtrim function that takes as a parameter, the value/character set that should be trimmed.
I think it might be something way too obvious that I don't see, but at this point I feel like I could use some help.

You can use the following piece of code to do that for you:
var a = "\r\n some random text \r\n";
a = a.replace(new RegExp('\r\n$'), '');
Here, $ matches end of input.
You can refer to the regular expressions guide here to find out more about regex in JS.
EDIT:
If you really need a function for this:
var rTrimRegex = new RegExp('\r\n$');
var rTrim = function(input){
return input.replace(rTrimRegex, '');
}
And then use it inside your code maybe like:
var str = 'my name is foo\r\n\r\n';
str = rTrim(str);

Related

Check first character of a word in a string begins with #

A few days ago I posted a similar question, but I do not quite understand the principle. Are there good resources where the replace function combined with regular expressions is explained?
Anyways, right now I have the following problem: A string which starts with # should be placed in an link. So #test should be replaced to #test .
Also, these rules should apply:
The string can only contain one #, which is at the beginning.
If there are more strings, also replace them. I thought you can do this by putting /g behind the regex?
This is what I have so far:
value = "is #test";
var text = value.replace(/^.*(#)(\w+).*$/, "<a href='$2'>$1$2</a>");
My output
#test
EDIT:
The link is now working. However, the word "is" is missing.
You need to capture the ambient text:
value = "is #test or what";
var text = value.replace(/^(.*)#(\w+)(.*)$/, "$1<a href='$2'>#$2</a>$3");
Or just capture less:
var text = value.replace(/#(\w+)/, "<a href='$1'>#$1</a>");
When performing a .replace(), you need to include all the characters in the RegExp that you wish to replace, preserving the ones you want to keep with parentheses.
var test = 'is #test';
function makeAt(string){
return string.replace(/^.*(#)(\w+).*$/, "<a href='$2'>$1$2</a>");
}
console.log(makeAt(test));

Line break javascript doesn't insert new line "\n"

I've been trying to wrap my head around this whole line break thing, and I've searched and researched my soul out here. I can't seem to find an answer to my specific problem here. I want to fetch the input from a textarea and put it in an array with new lines. All it does is put a comma between the words, and it seems it only adds multiple commas to where the line breaks are supposed to be. When I add < br / >, all it does is exclude the letter b from the text.
function Wordscount() {
var pText = document.getElementById("myTextarea").value.split(/[\n <>.,\?]/);
document.getElementById("text").innerHTML = pText;
It basically just looks like this when I test it :
I am new to Javascript, and I wouldn't have gone for this solution unless this was the method our professor told us to use. I'm really frustrated here, and I'm just trying to get the hang of this.
Splitting a string turns it into an array. Treating an array as a string is equivalent to calling yourArray.join(','). Since you don't want to add commas, don't just treat the array as a string.
If you want to put HTML line breaks in, then you need to do so explicitly.
var array_of_lines = document.getElementById("myTextarea").value.split("\n");
var string_of_html = array_of_lines.join("<br>");
document.getElementById("text").innerHTML = string_of_html;
If you don't want HTML special characters to be treated as having special meaning, then convert each line to a text node and append it instead.
var array_of_lines = document.getElementById("myTextarea").value.split("\n");
document.getElementById("text").innerHTML = "";
while(var text = array_of_lines.unshift()) {
document.getElementById("text").appendChild(
document.createTextNode(text)
);
document.getElementById("text").appendChild(
document.createElement("br")
);
}

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);

Get Newline character using javascript

In my html page I have to split user input based on newline character.
How to get newline character using javascript?
Please see the below code :
var str=document.getElementById('nwline').value;
var lines = str.split(/\r\n|\r|\n/g);
console.log(lines);
http://jsfiddle.net/asimshahiddIT/0yog7v83/
The resume of possible duplicate is using regex does allow you to ignore the OS you're using:
I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:
lines = foo.value.split(/\r\n|\r|\n/g);
In your case:
var splittedValues = originalTxt.split(/\r\n|\r|\n/g);

Trying to use Javascript regex to grab a section of "&" delimited text whether or not it's the last value

My text looks similar to this:
action=addItem&siteId=4&lang_locale=en_US&country=US&catalogId=1&productId=417689&displaySize=7&skuSize=2194171&qty=1&pil=7&psh=had+AIRJRnjbp7+rGivIKg00
and I want to replace the value of 'psh'. It may sometimes not be the last value (it may be followed by &something=else).
I've tried doing these lines of code:
var text = text.replace(/&psh=.*(?=&|$)/, "&psh=" + data.psh);
var text = text.replace(/&psh=.*(?=[&|$]+)/, "&psh=" + data.psh);
var text = text.replace(/(?:&psh=)(.*)(?=[&|$]+)/, data.psh);
None of them work for both situations. Use this site to check regexes.
This should work:
var text = text.replace(/&psh=[^&]*/, "&psh=" + data.psh);
[^&]* matches a string of any length that consists of any characters except &, therefore the match will continue until the end of the string or until (but not including) the next &, whichever comes first.
Tim's answer may work, but I fear it is not the best possible answer. The string you are giving as an example looks a lot like a url. If it is, that means there can sometimes be a pound sign in it as well (#). To compensate for that you actually need to modify your code to look like this:
var text = text.replace(/&psh=[^&#]*/, "&psh=" + data.psh);
Notice the # which was added in order to not get tripped up by anchor tags in the url.

Categories

Resources