Regular expression for removing whitespaces - javascript

I have some text which looks like this -
" tushar is a good boy "
Using javascript I want to remove all the extra white spaces in a string.
The resultant string should have no multiple white spaces instead have only one. Moreover the starting and the end should not have any white spaces at all. So my final output should look like this -
"tushar is a good boy"
I am using the following code at the moment-
str.replace(/(\s\s\s*)/g, ' ')
This obviously fails because it doesn't take care of the white spaces in the beginning and end of the string.

This can be done in a single String#replace call:
var repl = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// gives: "tushar is a good boy"

This works nicely:
function normalizeWS(s) {
s = s.match(/\S+/g);
return s ? s.join(' ') : '';
}
trims leading whitespace
trims trailing whitespace
normalizes tabs, newlines, and multiple spaces to a single regular space

Try this:
str.replace(/\s+/g, ' ').trim()
If you don't have trim add this.
Trim string in JavaScript?

Since everyone is complaining about .trim(), you can use the following:
str.replace(/\s+/g,' ' ).replace(/^\s/,'').replace(/\s$/,'');
JSFiddle

This regex may be useful to remove the whitespaces
/^\s+|\s+$/g

Try:
str.replace(/^\s+|\s+$/, '')
.replace(/\s+/, ' ');

try
var str = " tushar is a good boy ";
str = str.replace(/^\s+|\s+$/g,'').replace(/(\s\s\s*)/g, ' ');
first replace is delete leading and trailing spaces of a string.

Related

replace \r\n with < br /> as text

Trying for 2 hours to replace \r\n with < br/> but it seems to be impossible.
I don't know what i'm doing! Please help!
const text = '"Hello!\r\n\r\nThis is a dog!'
const checkText = str=> {
const match = /\r|\n/.exec(text);
if (match) {
//return str.replace(/(?:\\[rn]|[\r\n]+)+/g, '<br/>');
return str.replace('/r/n', '<br/>');
}
return str;
};
checkText(text)
Just do this:
text.replace(/\r\n/g, '<br/>');
Covering all the possible new line character combinations.
String tmp = s.replaceAll("\r\n", "<br>"); // Windows
tmp = tmp.replaceAll("\r", "<br>"); // Old MAC
return tmp.replaceAll("\n", "<br>"); // Linux / UNIX
You may try:
(text+ '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
There are multiple things wrong with your code:
String.prototype.replace only replaces the first occurrence of a string. You need to use a regex argument with the /g flag to replace all occurrences.
Escapes use a backslash, not a forward slash: Use \r\n, not /r/n.
checkText returns a string, but your call-site doesn't do anything with the returned string - it's just dropped. Strings are immutable in JavaScript.
I don't recommend using strings to hold HTML because it can (very easily) cause HTML-injection (including <script>-injection) attacks.
Instead, do one of the following:
Use String.prototype.split and HTML-encode each string in the array and join with "<br />".
Add the string directly to the document with .textContent (don't use innerText anymore) and give the parent element the CSS style whitespace: pre-wrap;.

javascript - replace dash (hyphen) with a space

I have been looking for this for a while, and while I have found many responses for changing a space into a dash (hyphen), I haven't found any that go the other direction.
Initially I have:
var str = "This-is-a-news-item-";
I try to replace it with:
str.replace("-", ' ');
And simply display the result:
alert(str);
Right now, it doesn't do anything, so I'm not sure where to turn. I tried reversing some of the existing ones that replace the space with the dash, and that doesn't work either.
Thanks for the help.
This fixes it:
let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);
There were two problems with your code:
First, String.replace() doesn’t change the string itself, it returns a changed string.
Second, if you pass a string to the replace function, it will only replace the first instance it encounters. That’s why I passed a regular expression with the g flag, for 'global', so that all instances will be replaced.
replace() returns an new string, and the original string is not modified. You need to do
str = str.replace(/-/g, ' ');
I think the problem you are facing is almost this: -
str = str.replace("-", ' ');
You need to re-assign the result of the replacement to str, to see the reflected change.
From MSDN Javascript reference: -
The result of the replace method is a copy of stringObj after the
specified replacements have been made.
To replace all the -, you would need to use /g modifier with a regex parameter: -
str = str.replace(/-/g, ' ');
var str = "This-is-a-news-item-";
while (str.contains("-")) {
str = str.replace("-", ' ');
}
alert(str);
I found that one use of str.replace() would only replace the first hyphen, so I looped thru while the input string still contained any hyphens, and replaced them all.
http://jsfiddle.net/LGCYF/
In addition to the answers already given you probably want to replace all the occurrences. To do this you will need a regular expression as follows :
str = str.replace(/-/g, ' '); // Replace all '-' with ' '
Use replaceAll() in combo with trim() may meet your needs.
const str = '-This-is-a-news-item-';
console.log(str.replaceAll('-', ' ').trim());
Imagine you end up with double dashes, and want to replace them with a single character and not doubles of the replace character. You can just use array split and array filter and array join.
var str = "This-is---a--news-----item----";
Then to replace all dashes with single spaces, you could do this:
var newStr = str.split('-').filter(function(item) {
item = item ? item.replace(/-/g, ''): item
return item;
}).join(' ');
Now if the string contains double dashes, like '----' then array split will produce an element with 3 dashes in it (because it split on the first dash). So by using this line:
item = item ? item.replace(/-/g, ''): item
The filter method removes those extra dashes so the element will be ignored on the filter iteration. The above line also accounts for if item is already an empty element so it doesn't crash on item.replace.
Then when your string join runs on the filtered elements, you end up with this output:
"This is a news item"
Now if you were using something like knockout.js where you can have computer observables. You could create a computed observable to always calculate "newStr" when "str" changes so you'd always have a version of the string with no dashes even if you change the value of the original input string. Basically they are bound together. I'm sure other JS frameworks can do similar things.
if its array like
arr = ["This-is-one","This-is-two","This-is-three"];
arr.forEach((sing,index) => {
arr[index] = sing.split("-").join(" ")
});
Output will be
['This is one', 'This is two', 'This is three']

How to replace all the \ from a string with space in javascript?

For example:
var str="abc\'defgh\'123";
I want to remove all the \ using Javascript. I have tried with several functions but still can't replace all the forward slashes.
I've posted a huuuge load of bollocks on JS and multiple replace functionality here. But in your case any of the following ways will do nicely:
str = str.replace('\\',' ');//Only replaces first occurrence
str = str.replace(/\\/g,' ');
str = str.split('\\').join(' ');
As #Guillaume Poussel pointed out, the first approach only replaces one occurrence of the backslash. Don't use that one, either use the regex, or (if your string is quite long) use the split().join() approach.
Just use the replace function like this:
str = str.replace('\\', ' ');
Careful, you need to escape \ with another \. The function returns the modified string, it doesn't modify the string on which it is called, so you need to catch the return value like in my example! So just doing:
str.replace('\\', ' ');
And then using str, will work with the original string, without the replacements.
str="abc\\'asdf\\asdf"
str=str.replace(/\\/g,' ')
You want to replace all '\' in your case, however, the function replace will only do replacing once if you use '\' directly. You have to write the pattern as a regular expression.
See http://www.w3schools.com/jsref/jsref_replace.asp.
Try:
string.replace(searchvalue,newvalue)
In your case:
str.replace('\\', ' ');
Using string.replace:
var result = str.replace('\\', ' ');
Result:
"abc 'defgh '123"

Javascript textarea flatten string

var newString = someString.replace(/\n/, '#');
Works great, when i do an alert;
alert(newString);
It appears as this:
"Firstline
#Secondline
#ThirdLine"
I wish for it to display:
"Firstline#SecondLine#Thirdline"
This is screwing up my other coding!
Can anyone help?
Some OS have \r\n for newlines. So, add an optional carriage return character to the RegExp. Also, add a global flag to your RegExp if you want to replace all occurrences:
var newString = someString.replace(/\r?\n/g, '#');
Try using...
var newString = someString.replace(/\n\r?/g, '#'))
Try:
someString.replace(/[\r\n]+/, '#');
If you are trying to prepend # to each line you might want this:
someString.replace(/^/gm, "#")
#Firstline
#Secondline
#ThirdLine
I would recommmend the following
function flatString(s) {
// remove line separators (windows and linux) and trim multiple spaces
s = s.replace(/\r\n/g, ' ')
.replace(/\r/g, ' ')
.replace(/\n/g, ' ')
.replace(/[ ]+/g, ' ')
.trim();
return s;
}
You first delete the Windows line ends (\r\n are always together), then you remove the single characters (for linux line ends).
At this point, you flatted the string. However, depending on how many newline characters you had, you may end up with many spaces. So we try to convert all n-spaces to single spaces, and lastly do a trim so we get the shortest string as possible.
NOTE: this can be further optimized to try to run the most regex possibilities in a single execution, but it makes the cut at least.

Regex for matching spaces not preceded by commas

I need to convert a string like this:
tag, tag2, longer tag, tag3
to:
tag, tag2, longer-tag, tag3
To make this short, I need to replace spaces not preceded by commas with hyphens, and I need to do this in Javascript.
I think this should work
var re = new RegExp("([^,\s])\s+" "g");
var result = tagString.replace(re, "$1-");
Edit: Updated after Blixt's observation.
mystring.replace(/([^,])\s+/i "$1-"); There's a better way to do it, but I can't ever remember the syntax
[^,] = Not a comma
Edit Sorry, didn't notice the replace before. I've now updated my answer:
var exp = new RegExp("([^,]) ");
tags = tags.replace(exp, "$1-");
text.replace(/([^,]) /, '$1-');
Unfortunately, Javascript doesn't seem to support negative lookbehinds, so you have to use something like this (modified from here):
var output = 'tag, tag2, longer tag, tag3'.replace(/(,)?t/g, function($0, $1){
return $1 ? $0 : '-';
});
[^,] - The first character is not comma, the second character is space and it searches for that kind of string
([a-zA-Z] ){1,}
Maybe? Not tested. something like that.

Categories

Resources