How to replace all spaces in a string - javascript

I have two html text input, out of that what ever user type in first text box that need to reflect on second text box while reflecting it should replace all spaces to semicolon. I did to some extant and it replacing for first space not for all, I think I need to use .each function of Jquery, I have used .each function but I didn't get the result see this
HTML :
Title : <input type="text" id="title"><br/>
Keyword : <input type="text" id="keyword">
Jquery:
$('#title').keyup(function() {
var replaceSpace = $(this).val();
var result = replaceSpace.replace(" ", ";");
$("#keyword").val(result);
});
Thanks.

var result = replaceSpace.replace(/ /g, ";");
Here, / /g is a regex (regular expression). The flag g means global. It causes all matches to be replaced.

Pure Javascript, without regular expression:
var result = replaceSpacesText.split(" ").join("");

takes care of multiple white spaces and replaces it for a single character
myString.replace(/\s+/g, "-")
http://jsfiddle.net/aC5ZW/340/

VERY EASY:
just use this to replace all white spaces with -:
myString.replace(/ /g,"-")

Simple code for replace all spaces
var str = 'How are you';
var replaced = str.split(' ').join('');
Out put:
Howareyou

$('#title').keyup(function () {
var replaceSpace = $(this).val();
var result = replaceSpace.replace(/\s/g, ";");
$("#keyword").val(result);
});
Since the javascript replace function do not replace 'all', we can make use the regular expression for replacement. As per your need we have to replace all space ie the \s in your string globally. The g character after the regular expressions represents the global replacement. The seond parameter will be the replacement character ie the semicolon.

I came across this as well, for me this has worked (covers most browsers):
myString.replace(/[\s\uFEFF\xA0]/g, ';');
Inspired by this trim polyfill after hitting some bumps:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim#Polyfill

You can do the following fix for removing Whitespaces with trim and # symbol:
var result = string.replace(/ /g, ''); // Remove whitespaces with trimmed value
var result = string.replace(/ /g, '#'); // Remove whitespaces with *#* symbol

Related

How do I remove the string in brackets only from the beginning of the entire string?

I have tried using replace for removing the string in the brackets. But this doesnt work. I want to remove only in the beginning brackets.
var string="(I want to delete this) helloo (not this)";
var replacedString=string.replace(/ *\([^)]*\) */g, "");
You could look for the first bracket at start and for a closing bracket of the string and then replace it.
var string = "(I want to delete this) helloo (not this)",
result = string.replace(/^\([^)]*\)/, '');
console.log(result);
Try below regex, without /g flag
\((.+?)\)
You will get the result in group 1 if you want to preserve brackets,
Regex Demo
This should work in most, if not all, instances:
myString.replace(/\((.*?)\)/, '$1')

Regex to get the text between two characters?

I want to replace a text after a forward slash and before a end parantheses excluding the characters.
My text:
<h3>notThisText/IWantToReplaceThis)<h3>
$('h3').text($('h3').text().replace(regEx, 'textReplaced'));
Wanted result after replace:
notThisText/textReplaced)
I have tried
regex = /([^\/]+$)+/ //replaces the parantheses as well
regex = \/([^\)]+) //replaces the slash as well
but as you can see in my comments neither of these excludes both the slash and the end parantheses. Can someone help?
A pattern like /(?<=\/)[^)]+(?=\))/ won't work in JS as its regex engine does not support a lookbehind construct. So, you should use one of the following solutions:
s.replace(/(\/)[^)]+(\))/, '$1textReplaced$2')
s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')
s.replace(/(\/)[^)]+/, '$1textReplaced')
s.replace(/\/[^)]+\)/, '/textReplaced)')
The (...) forms a capturing group that can be referenced to with $ + number, a backreference, from the replacement pattern. The first solution is consuming / and ), and puts them into capturing groups. If you need to match consecutive, overlapping matches, use the second solution (s.replace(/(\/)[^)]+(?=\))/, '$1textReplaced')). If the ) is not required at the end, the third solution (replace(/(\/)[^)]+/, '$1textReplaced')) will do. The last solution (s.replace(/\/[^)]+\)/, '/textReplaced)')) will work if the / and ) are static values known beforehand.
You can use str.split('/')
var text = 'notThisText/IWantToReplaceThis';
var splited = text.split('/');
splited[1] = 'yourDesireText';
var output = splited.join('/');
console.log(output);
Try Following: In your case startChar='/', endChar = ')', origString=$('h3').text()
function customReplace(startChar, endChar, origString, replaceWith){
var strArray = origString.split(startChar);
return strArray[0] + startChar + replaceWith + endChar;
}
First of all, you didn't define clearly what is the format of the text which you want to replace and the non-replacement part. For example,
Does notThisText contain any slash /?
Does IWantToReplaceThis contain any parentheses )?
Since there are too many uncertainties, the answer here only shows up the pattern exactly matches your example:
yourText.replace(/(\/).*?(\))/g, '$1textReplaced$2')
var text = "notThisText/IWantToReplaceThis";
text = text.replace(/\/.*/, "/whatever");
output : "notThisText/whatever"`

jQuery: How to trim new line and tab characters between words

Hi I am getting new line(\n) and tab(\t) characters between words and I was trying to trim those by using $.trim() function but its not working. So can anyone have some solution for this type of problem.
Ex:
var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str));
the above code is not working.
str.replace(/\s+/g, " "); //try this
reference replace
\s matches any newline or tab or white-space
You can do this:
var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str.replace(/[\t\n]+/g,' ')));
// results is "Welcome To Beautiful World"
That is expected. trim only takes care of leading and trailing whitespace.
Instead, use
str.split(/\s/).join(' ');
In your example, this returns
"Welcome To Beautiful World"
You can use replace with a regular expression :
var str = "Welcome\n\tTo\n\nBeautiful\t\t\t\nWorld";
alert($.trim(str.replace(/[\t\n]+/g, ' ')));
Demo

How to remove the special characters from a string using javascript

I have the below String value to be displayed in text area and i want to remove the first characters ##*n|n from the string .
The string is as follows :
Symbol-001
##*n|nClaimant Name
##*n|nTransaction
I have used the below code to deal with removing the special characters
var paramVal1 = parent.noteText; //paramVal1 will have the string now
var pattern = /[##*n|n]/g;
var paramVal1 = paramVal1.replace(pattern,'');
document.getElementById("txtNoteArea").value = paramval1;//appending the refined string to text area
For the above used code am getting the out put string as below
Symbol-001
|Claimat Name //here 'n' is missing and i have an extra '|' character
|Transactio //'n' is missing here too and an extra '|' character
Kindly help to remove the characters ##*n|n without affecting the other values
What your regex is saying is "remove any of the following characters: #|*n". Clearly this isn't what you want!
Try this instead: /##\*n\|n/g
This says "remove the literal string ##*n|n". The backslashes remove the special meaning from * and |.
You are using regular expression reserved chars in your pattern, you need to escape them
You can use this expression:
var pattern = /[\#\#\*n\|n]/g;
i think use this /[##*n\|n]/g regEx
If you want to replace the first occurrence as you say on your question, you don't need to use regex. A simple string will do, as long as you escape the asterisk:
var str = "Symbol-001 ##*n|nClaimant Name ##*n|nTransaction";
var str2 = str.replace("##\*n|n", ""); //output: "Symbol-001 Claimant Name ##*n|nTransaction"
If you want to replace all the occurrences, you can use regex, escaping all the characters that have a special meaning:
var str3 = str.replace(/\#\#\*n\|n/g, ""); //output: "Symbol-001 Claimant Name Transaction"
Have a look at this regex builder, might come in handy - http://gskinner.com/RegExr/

Replace multiple whitespaces with single whitespace in JavaScript string

I have strings with extra whitespace characters. Each time there's more than one whitespace, I'd like it be only one. How can I do this using JavaScript?
Something like this:
var s = " a b c ";
console.log(
s.replace(/\s+/g, ' ')
)
You can augment String to implement these behaviors as methods, as in:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
This now enables you to use the following elegant forms to produce the strings you want:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();
Here's a non-regex solution (just for fun):
var s = ' a b word word. word, wordword word ';
// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"
// or ES2015:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
Can even substitute filter(n => n) with .filter(String)
It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?
If that's the case, you'll need a regex like this:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
mystring = mystring.replace(/\s+$/g,' ');
Hope that helps.
jQuery.trim() works well.
http://api.jquery.com/jQuery.trim/
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
I want to replace multiple occurences of whitespace inside the string with a single space
...and... I do not want whitespaces in the beginnin or end of the string (trim)
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
var x = " Test Test Test ".split(" ").join("");
alert(x);
Try this.
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
the result will be
string 1
What happened here is that it will trim the outside spaces first using trim() then trim the inside spaces using .replace(/\s+/g, ' ').
How about this one?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs "my test string with crazy stuff is cool "
This one gets rid of any tabs as well
If you want to restrict user to give blank space in the name just create a if statement and give the condition. like I did:
$j('#fragment_key').bind({
keypress: function(e){
var key = e.keyCode;
var character = String.fromCharCode(key);
if(character.match( /[' ']/)) {
alert("Blank space is not allowed in the Name");
return false;
}
}
});
create a JQuery function .
this is key press event.
Initialize a variable.
Give condition to match the character
show a alert message for your matched condition.

Categories