Preserve non-break space &nbsp in jQuery trim function - javascript

I want to trim only regular whitespace and preserve &nbsp non-break spaces. What is my best bet?
Update: By trim, I mean either leading or trailing. I specifically need to eliminate leading whitespace other than &nbsp, but I will appreciate answers that do the same for also trailing or just trailing.

If the string is the content of an HTML tag you can cheat a bit, using:
var result = $( '#element' ).html().trim();
which will not trim because it will literally be in the string.
If the string is not in a tag you could try:
var result = $( '<p>' + the_string + '</p>' ).html().trim();
which should do the same thing.

Replace all white spaces with blank.
var dest = 'test value';
result_val=dest.split(" ").join("");
demo

If you want to remove empty characters in the middle of the string, you can use this (note the first parameter means any amount of whitespace but shouldn't match an ):
var newString = s.replace(/\s+/g, '');
If not (meaning only remove white space at the start/end of the string), you can use
var newString = s.trim();

Related

Trim last + from string in jQuery

I'm trying to generate a link using jQuery and need to trim the last '+' sign off the end. Is there a way to detect if there is one there, and then trim it off?
So far the code removes the word 'hotel' and replaces spaces with '+', I think I just need another replace for the '+' that shows up sometimes but not sure how to be super specific with it.
var nameSearch = name.replace("Hotel", "");
nameSearch = nameSearch.replace(/ /g, "+");
Thanks
You could simply use String.prototype.trim() before you call replace, in order to remove the leading and trailing white-space from the String:
var nameSearch = name.trim().replace("Hotel", "").replace(/ /g, "+");
References:
String.prototype.trim().
You can target the end of the string within a Regex with the $ character. You can remove the + signs from the end like this.
nameSearch = nameSearch.replace(/\+*$/g, "");
But even better, as David Thomas pointed out, you should call trim on the string before your manipulation, so it won't have any leading and trailing white-spaces, hence you won't need to trim the + signs.

Regex for both newline and backslash for Replace function

I am using a replace function to escape some characters (both newline and backslash) from a string.
Here is my code:
var str = strElement.replace(/\\/\n/g, "");
I am trying to use regex, so that I can add more special characters if needed. Is this a valid regex or can someone tell me what am I doing wrong here?
You're ending the regex early with an unescaped forward slash. You also want to use a set to match individual characters. Additionally you might want to add "\r" (carriage return) in as well as "\n" (new line).
This should work:
var str = strElement.replace(/[\\\n\r]/g, "");
This is not a valid regex as the slash is a delimiter and ends the regex. What you probably wanted is the pipe (|), which is an alternation:
var str = strElement.replace(/\\|\n/g, "");
In case you need to extend it in the future it may be helpful to use a character class to improve readability:
var str = strElement.replace(/[\\\nabcx]/g, "");
A character class matches a single character from it's body.
This should work. The regular expression replaces both the newline characters and the backslashes in escaped html text:
var str = strElement.replace(/\\n|\\r|\\/g, '');

Javascript if string contains a space replace the space with a dash

I'm trying to write some code that will check if a previously defined variable has a space, and if it does, replace the space with a dash. This will be nested in another function.
function foo(){
// If stateName has a space replaces the space with a dash
window.open('http://website.html/state-solar-policy/' + stateName);
}
Use this regex:
stateName.replace(/\s/g,"-");
It will replace all white spaces chars with a dash (-)
Note that the regex will cause no troubles if the string doesn't have a space in it.
It replaces every white-space if finds with a dash, if it doesn't find, it does nothing.
var string = "blah blah blah"
var new_string = string.replace(" ", "-");
var string="john doe is great";
var dashedstring=string.split(" ").join("-");

Removing Unwanted Spaces Using javascript

In my application i want to remove the unwanted space from starting and ending.And also if there have more than space between words also remove them leaving one space.
How can i do this?
Try this:
//remove leading spaces
content = content.replace(/^\s+/g,'');
//remove trailing spaces
content = content.replace(/\s+$/g,'');
//remove whitespaces in the middle
content = content.replace(/\s+/g,' ');
This should work to remove leading and trailing spaces, and reduce two or more spaces to a single space:
str.replace(/^\s+|\s+$/, '').replace('/\s\s+/', ' ')
You can use jQuery trim method.This function remove all new lines and all spaces leading or trailing from input string.
var str = ' it is a test string ';
alert($.trim(str));

Javascript - How to remove all extra spacing between words

How can I remove all extra space between words in a string literal?
"some value"
Should become
"some value"
Also,
" This should become something else too . "
Becomes
"This should become something else too ."
Do not worry about moving the .. Just as above is fine. I know I can use $.trim(str) to achieve the trailing/ending space removal. But, I'm not sure how to do the 1 space between words trick.
var string = " This should become something else too . ";
string = string.replace(/\s+/g, " ");
This code replaces a consecutive set of whitespace characters (\s+) by a single white space. Note that a white-space character also includes tab and newlines. Replace \s by a space if you only want to replace spaces.
If you also want to remove the whitespace at the beginning and end, include:
string = string.replace(/^\s+|\s+$/g, "");
This line removes all white-space characters at the beginning (^) and end ($). The g at the end of the RegExp means: global, ie match and replace all occurences.
var str = " This should become something else too . ";
str = str.replace(/ +(?= )/g,'');
Here's a working fiddle.
In case we want to avoid the replace function with regex,
We can achieve same result by
str.split(' ').filter(s => s).join(' ')
// var str = " This should become something else too . ";
// result is "This should become something else too ."
First, split the original string with space, then we will have empty string and words in an array. Second, filter to remain only words, then join all words with a whitespace.
var str = " This should become something else too . "
$.trim(str).replace(/\s(?=\s)/g,'')
This uses lookahead to replace multiple spaces with a single space.
jsFiddle Example
" This should become something else too . ".replace(/[\s\t]+/g,' ');
Another (perhaps easier to understand) regexp replacement that will do the trick:
var input = /* whatever */;
input = input.replace(/ +/g, ' ');
The regexp matches one or more spaces, so the .replace() call replaces every single or repeated space with a single space.
var str = 'some value';
str.replace(/\s\s+/g, ' ');

Categories

Resources