How to remove the white space at the start of the string - javascript

I want to remove the white space which is there in the start of the string
It should remove only the space at the start of the string, other spaces should be there.
var string=' This is test';

This is what you want:
function ltrim(str) {
if(!str) return str;
return str.replace(/^\s+/g, '');
}
Also for ordinary trim in IE8+:
function trimStr(str) {
if(!str) return str;
return str.replace(/^\s+|\s+$/g, '');
}
And for trimming the right side:
function rtrim(str) {
if(!str) return str;
return str.replace(/\s+$/g, '');
}
Or as polyfill:
// for IE8
if (!String.prototype.trim)
{
String.prototype.trim = function ()
{
// return this.replace(/^\s+|\s+$/g, '');
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
if (!String.prototype.trimStart)
{
String.prototype.trimStart = function ()
{
// return this.replace(/^\s+/g, '');
return this.replace(/^[\s\uFEFF\xA0]+/g, '');
};
}
if (!String.prototype.trimEnd)
{
String.prototype.trimEnd = function ()
{
// return this.replace(/\s+$/g, '');
return this.replace(/[\s\uFEFF\xA0]+$/g, '');
};
}
Note:
\s: includes spaces, tabs \t, newlines \n and few other rare characters, such as \v, \f and \r.
\uFEFF: Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
\xA0: ASCII 0xA0 (160: non-breaking space) is not recognised as a space character

Try to use javascript's trim() function, Basically it will remove the leading and trailing spaces from a string.
var string=' This is test';
string = string.trim();
DEMO
So as per the conversation happened in the comment area, in order to attain the backward browser compatibility just use jquery's $.trim(str)
var string=' This is test';
string = $.trim(string)

You can use String.prototype.trimStart(). Like this:
myString=myString.trimStart();
An if you want to trim the tail, you can use:
myString=myString.trimEnd();
Notice, this 2 functions are not supported on IE. For IE you need to use polyfills for them.

You should use javascript trim function
var str = " Hello World! ";
alert(str.trim());
This function can also remove white spaces from the end of the string.

Easiest solution: (ES10 feature trimStart())
var string= 'This is a test';
console.log(string.trimStart());

.trimLeft() can be used for this.
const str = " string ";
console.log(str.trimLeft()); // => "string "

Just a different and a not so efficient way to do it
var str = " My string";
function trim() {
var stringStarted = false;
var newString = "";
for (var i in str) {
if (!stringStarted && str[i] == " ") {
continue;
}
else if (!stringStarted) {
stringStarted = true;
}
newString += str[i];
}
return newString;
}
console.log(trim(str));
I am really sure this doesn't work for anything else and is not the most optimum solution, but this just popped into my mind

You want to remove the space (i.e whitespace) at the beginning of the string. So, could not use standard jquesy .trim(). You can use the regex to find and replace the whitespace at the beginning of the string.
Try this:
.replace(/^\s+/g, "")
Read this post
Try this:
var string=' This is test ';
alert(string.replace(/^\s+/g, ""));
Working Example
OR if you want to remove the whitespace from the beginning and end then use .trim()

var string=' This is test';
$.trim(string);

Related

Iterating through string and replacing the spaces not working as expected

So I'm trying to return the string with "%20" in between each space, except if there is a space at the beginning or end, where it will be removed instead (eg " Lighthouse Labs " becomes "Lighthouse%20Labs"). For some reason though, my first if statement isn't working, and if there is a space at the beginning or end, it applies the code inside the if statement to ALL the spaces and I have no idea why. I must be fundamentally misunderstanding something here. Any help appreciated!
const urlEncode = function (text) {
for (let i = 0; i < text.length; i++) {
if (text.charAt(0) === " " || text.charAt(text.length - 1) === " ") {
return text.split(" ").join("");
} else {
return text.split(" ").join("%20")
}
}
return text;
};
console.log(urlEncode("Lighthouse Labs")); // Lighthouse%20Labs
console.log(urlEncode(" Lighthouse Labs ")); // LighthouseLabs
console.log(urlEncode("blue is greener than purple for sure")); //blue%20is%20greener%20than%20purple%20for%20sure
console.log(urlEncode(" blue is greener than purple for sure")); //blueisgreenerthanpurpleforsure
console.log(urlEncode("blue is greener than purple for sure "));
//blueisgreenerthanpurpleforsure
You can use trim and replace:
const urlEncode = function (text) {
const regex = / /g
return text.trim().replace(regex, '%20');
}
use this function:
const urlEncode = function (text){
return text.trim().replace(/\s+/g, '%20')
}
Trim() function will remove spaces from beginning and ending of text. The first argument of replace method is a regex that says every whitespace replaced by second argument, the + quantifier means that if there is consecutive whitespaces replace all of them with only one '%20'

JavaScript replace all but last whilst preserving original line breaks

I have some code which outputs as follows:
function replaceAllButLast(str, splitRegex, pOld, pNew) {
var parts = str.split(splitRegex)
if (parts.length === 1) return str
return parts.slice(0, -1).join(pNew) + pOld + parts.slice(-1)
}
var str = "fred\r\nfred\r\nfred\r\n"
var desiredResult = replaceAllButLast(str, /(?:\r?\n|\r)/, '\n', '\n+')
console.log(desiredResult)
The result is nearly as desired. However, the code assumes that the regex split operation is splitting on \n and thus is replacing it with \n
However, it may actually be splitting on \r\n (windows - as in the example) or \r (old macs)
Does anyone have some code that would give the same output as the code here BUT will preserve the original line break characters whilst still adding the + after a newline (except on the last line).
I am using pure vanilla JavaScript.
PS I must use the regex /(?:\r?\n|\r)/
PPS There is no need to use .split().
This will keep the last newline as it is but others added a +, see replace
var str = "fred\r\nfred\r\nfred\r\n";
var splitRegexp = new RegExp(/(?:\r?\n|\r)/, 'g')
var newstr = str.replace(splitRegexp, function(match, offset, string) {
var follow = string.slice(offset);
var isLast = follow.match(splitRegexp).length == 1;
if (!isLast) {
return match + '+';
} else {
return match;
}
})
console.log(newstr)
I've replaced your regexp with visible chars so you can see what's going on:
var input = "fredEOLfredENDLfredFINfred";
input = input.replace(/(EOL|ENDL|FIN)/g, "$1+");
console.log(input);

Remove an underscore with Regex in JavaScript

Like the title says, i would like to remove an underscore within a String with a regex. This is what i have:
function palindrome(str) {
str = str.toLowerCase().replace(/[^a-zA-Z]/g, '',/\s/g, '',/[0-9]/g,'');
if (str.split("").reverse().join("") !== str) {
return false;
}
else {
return true;
}
}
palindrome("eye");
Use .replace(/_/g, "") to remove all underscores or use .replace(/_/g, " ") to replace them with a space.
Here is an example to remove them:
var str = "Yeah_so_many_underscores here";
var newStr = str.replace(/_/g, "");
alert(newStr);
You can use .replace to achieve this. Use the following code. It will replace all _ with the second parameter. In our case we don't need a second parameter so all _ will be removed.
<script>
var str = "some_sample_text_here.";
var newStr = str.replace(/_/g , "");
alert ('Text without underscores : ' + newStr);
</script>
str.replace(/_/g, '');
This should work.
you can remove underscore from response or any string
like this: "hello_rizo"
Code:
var rizo="hello_rizo"
console.log('output', e.response.data.message.replace(/(^|_)./g, s => s.slice(-1).toUpperCase()));
output:
hellorizo

Remove all special characters except space from a string using JavaScript

I want to remove all special characters except space from a string using JavaScript.
For example,
abc's test#s
should output as
abcs tests.
You should use the string replace function, with a single regex.
Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
You can do it specifying the characters you want to remove:
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g, '');
The first solution does not work for any UTF-8 alphabet. (It will cut text such as Привіт). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).
search all not (word characters || space):
str.replace(/[^\w ]/, '')
I don't know JavaScript, but isn't it possible using regex?
Something like [^\w\d\s] will match anything but digits, characters and whitespaces. It would be just a question to find the syntax in JavaScript.
I tried Seagul's very creative solution, but found it treated numbers also as special characters, which did not suit my needs. So here is my (failsafe) tweak of Seagul's solution...
//return true if char is a number
function isNumber (text) {
if(text) {
var reg = new RegExp('[0-9]+$');
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '')) {
result += text[i];
}
}
return result;
}
return '';
}
const str = "abc's#thy#^g&test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
Try to use this one
var result= stringToReplace.replace(/[^\w\s]/g, '')
[^] is for negation, \w for [a-zA-Z0-9_] word characters and \s for space,
/[]/g for global
With regular expression
let string = "!#This tool removes $special *characters* /other/ than! digits, characters and spaces!!!$";
var NewString= string.replace(/[^\w\s]/gi, '');
console.log(NewString);
Result //This tool removes special characters other than digits characters and spaces
Live Example : https://helpseotools.com/text-tools/remove-special-characters
dot (.) may not be considered special. I have added an OR condition to Mozfet's & Seagull's answer:
function isNumber (text) {
reg = new RegExp('[0-9]+$');
if(text) {
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '') || (lower[i].trim() === '.')) {
result += text[i];
}
}
return result;
}
return '';
}
Try this:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' #
Test27919<alerts#imimobile.com> #elseif_1 $(PR_CONTRACT_START_DATE) == '20-09-2019' #
Sender539<rama.sns#gmail.com> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #
AdestraSID<hello#imimobile.co> #else_1#Test27919<alerts#imimobile.com>#endif_1#`;
const replaceString = input.split('$(').join('->').split(')').join('<-');
console.log(replaceString.match(/(?<=->).*?(?=<-)/g));
Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.
var str = 'abc'de#;:sfjkewr47239847duifyh';
alert(str.replace("'","").replace("#","").replace(";","").replace(":",""));
or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.

i want to create user defined function to trim a word in Javascript

how can i trim the word in Javascript.....???
If you can use jQuery, simply use $.trim().
If not, just add a trim method to the String prototype if the browser doesn't support it natively:
if(!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '')
}
}
Then you can use var newstring = somestring.trim();
If by trim, you mean remove extra whitepace, put this at the top of your script
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
And use it like this
var thestring = " hello ";
alert(thestring.trim());
You can add the function below
// Trim function in javascript
function Trim(str)
{
while (str.substring(0,1) == ' ') // check for white spaces from beginning
{
str = str.substring(1, str.length);
}
while (str.substring(str.length-1, str.length) == ' ') // check white space from end
{
str = str.substring(0,str.length-1);
}
return str;
}
Hope it helped...

Categories