How can I remove extra white space (i.e. more than one white space character in a row) from text in JavaScript?
E.g
match the start using.
How can I remove all but one of the spaces between "match" and "the"?
Use regex. Example code below:
var string = 'match the start using. Remove the extra space between match and the';
string = string.replace(/\s{2,}/g, ' ');
For better performance, use below regex:
string = string.replace(/ +/g, ' ');
Profiling with firebug resulted in following:
str.replace(/ +/g, ' ') -> 790ms
str.replace(/ +/g, ' ') -> 380ms
str.replace(/ {2,}/g, ' ') -> 470ms
str.replace(/\s\s+/g, ' ') -> 390ms
str.replace(/ +(?= )/g, ' ') -> 3250ms
See string.replace on MDN
You can do something like this:
var string = "Multiple spaces between words";
string = string.replace(/\s+/,' ', g);
Just do,
var str = "match the start using. Remove the extra space between match and the";
str = str.replace( /\s\s+/g, ' ' );
function RemoveExtraSpace(value)
{
return value.replace(/\s+/g,' ');
}
myString = Regex.Replace(myString, #"\s+", " ");
or even:
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"[ ]{2,}", options);
tempo = regex.Replace(tempo, #" ");
Using regular expression.
var string = "match the start using. Remove the extra space between match and the";
string = string.replace(/\s+/g, " ");
Here is jsfiddle for this
Sure, using a regex:
var str = "match the start using. Remove the extra space between match and the";
str = str.replace(/\s/g, ' ')
This can be done also with javascript logic. here is a reusable function I wrote for that task.
LIVE DEMO
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>result:
<span id="spn">
</span>
</div>
<input type="button" value="click me" onClick="ClearWhiteSpace('match the start using. JAVASCRIPT CAN BE VERY FUN')"/>
<script>
function ClearWhiteSpace(text) {
var result = "";
var newrow = false;
for (var i = 0; i < text.length; i++) {
if (text[i] === "\n") {
result += text[i];
// add the new line
newrow = true;
}
else if (newrow == true && text[i] == " ") {
// do nothing
}
else if (text[i - 1] == " " && text[i] == " " && newrow == false) {
// do nothing
}
else {
newrow = false;
if (text[i + 1] === "\n" && text[i] == " ") {
// do nothing it is a space before a new line
}
else {
result += text[i];
}
}
}
alert(result);
document.getElementById("spn").innerHTML = result;
return result;
}
</script>
</body>
</html>
Try this regex
var st = "hello world".replace(/\s/g,'');
or as a function
function removeSpace(str){
return str.replace(/\s/g,'');
}
Here is a working demo
Related
I am trying to get a code for a webpage using javascript. But I only want to return lines that include the word "array"
How can I remove all lines that do not include "array?"
I can't find anything online and my skills are very basic.
"I type this sentence because it says the post is mostly a code, and it still says the same so I'm just extending this."
function DOMtoString(document_root) {
var sourcecode = '',
node = document_root.firstChild;
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
sourcecode += node.outerHTML;
break;
case Node.TEXT_NODE:
sourcecode += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
sourcecode += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
sourcecode += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
sourcecode += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
break;
}
node = node.nextSibling;
}
var public = sourcecode.substring(
sourcecode.lastIndexOf("'[[") + 1,
sourcecode.lastIndexOf("]]';")
);
var matematika = sourcecode.substring(
sourcecode.lastIndexOf("var arraypaginascopia;") + 1,
sourcecode.lastIndexOf("var rellenado;")
);
var test = ("testovaci zprava");
var test2 = ("testovaci zprava druha");
var fail = ("Internal Error");
//arrayrespuestas
var currenturl = document.URL;
var url = currenturl.includes("www.liveworksheets.com/workbooks")
//return url;
if (url == true){
return matematika;
} else {
return public;
}
For example:
This is an example
This is an example
This is an example
This is a banana
This is an example
This is an example
This is a banana
The result should be:
This is a banana
This is a banana
In your question, you asked for the word array, but I'll use your example banana for the code.
const regex = /.*banana.*/gm;
// (.*) matches any character before and after the search string 'banana';
// The g flag is to match all occurrences and;
// The m flag is for a multi-line string
const str = `This is an example
This is an example
This is an example
This is a banana
This is an example
This is an example
This is a banana`;
console.log(str.match(regex));
In the end, I managed to do this.
const regex = /.*array.*/gm;
// (.*) matches any character before and after the search string 'banana';
// The g flag is to match all occurrences and;
// The m flag is for a multi-line string
const matematika2 = matematika;
// console.log(matematika2.match(regex));
return matematika2.match(regex);
The code is used in a HTML document, where when you press a button the first word in every sentence gets marked in bold
This is my code:
var i = 0;
while(i < restOftext.length) {
if (text[i] === ".") {
var space = text.indexOf(" ", i + 2);
var tekststykke = text.slice(i + 2, space);
var text = text.slice(0, i) + "<b>" + tekststykke + "</b>" + text.slice(i + (tekststykke.length + 2));
var period = text.replace(/<b>/g, ". <b>");
var text2 = "<b>" + firstWord + "</b>" + period.slice(space1);
i++
}
}
document.getElementById("firstWordBold").innerHTML = text2;
}
It's in the first part of the code under function firstWordBold(); where it says there is an error with
var space1 = text.indexOf(" ");
Looks like you're missing a closing quote on your string, at least in the example you provided in the question.
Your problem is the scope of the text variable. In firstWordBold change every text to this.text, except the last two where you re-define text
Also, if you want to apply bold to the first word this is easier...
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
It now works for me, with no errors and it applies bold to the first word.
Here's how the function ended up,
function firstWordBold() {
console.log('bolding!');
var space1 = this.text.indexOf(' ');
var firstWord = this.text.slice(0, space1);
var restOftext = this.text.slice(space1);
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
}
To make every first word bold, try this...
function firstWordBold() {
let newHTML = '';
const sentences = this.text.split('.');
for (let sentence of sentences) {
sentence = sentence.trim();
var space1 = sentence.indexOf(' ');
var firstWord = sentence.slice(0, space1);
var restOftext = sentence.slice(space1);
newHTML += '<b>' + firstWord + '</b>' + restOftext + ' ';
}
document.getElementById('test-div-2').innerHTML = newHTML;
}
One last edit, I didn't notice you had sentences ending with anything other that a period before. To split on multiple delimiters use a regex, like so,
const sentences = this.text.split(/(?<=[.?!])\s/);
I have set of numbers from an excel like this
05143
05250
05252
05156
05143
05441
05143
05031
05050
05101
05821
05822
05861
and after every 5th digit I wanted to add a ,
My problem is that after every 5th digit it considers a white space carriage as a digit and then split the items such as
05143 ↵0525 0↵052 50↵05 and so on...
and that's why , split is breaking. I tried to replace it as item.replace(/↵/g, ""); but its not working.
here is my code
item.replace(/↵/g, "")
console.log(item)
if(item.length > 5){
for (var i = 0; i < item.length; i += 5) {
chunks.push(item.substring(i, i + 5));
}
console.log(chunks)
var tempItem;
chunks.forEach(function(item2) {
if (tempItem == undefined) {
tempItem = "'" + item2 + "'";
} else {
tempItem = tempItem + ",'" + item2 + "'";
}
})
It's not clear from the question what character code you have in your string that cause the problem.
But I think that if you use this general replace you will solve.
item.replace(/\W/g, '')
it works when we write it as
item.split('\n')
I want to change
every single quote to double quote
and
every double quote to single quote
in jquery or js.
var myString = " tes't tes\"t tes\"t te'st ";
console.log(myString);
for (i = 0; i < myString.length; i++) {
console.log(myString[i]);
if (myString[i] == "'") {
myString[i] == "\"";
continue;
}
if (myString[i] == "\"") {
myString[i] == "'";
continue;
}
}
console.log(myString);
But my function is not working well.
Please correct me.
Inside the ifs you're not doing an assignment (myString[i] == "\"";) but a comparsion. This should probably be a single =. Only problem is, strings are immutable and thus this would not work as expected. Solution, build a new string:
function flipQuotes(str) {
var result = [], i = 0, lim = str.length, c;
for (; i < lim; i += 1) {
c = str.charAt(i);
switch(c) {
case '"':
result.push("'");
break;
case "'":
result.push('"');
break;
default:
result.push(c);
}
}
return result.join('');
}
var myString = " tes't tes\"t tes\"t te'st ";
console.log(
flipQuotes(myString) // => ' tes"t tes't tes't te"st '
);
You are doing comparations, not assingments. Also, you can't change a string that way, you need to create a new one:
var myString = " tes't tes\"t tes\"t te'st ";
console.log(myString);
var str = [];
for (i = 0; i < myString.length; i++) {
console.log(myString[i]);
if (myString[i] == "'") {
str.push("\"");
}
else if (myString[i] == "\"") {
str.push("'");
continue;
}
else
{
str.push(myString[i]);
}
}
str.join("");
console.log(str);
Check it in this live demo
Here is one more solution using different approach:
var myString = " tes't t%es\"t tes\"t te'st ",
result = myString.replace(/%/g, '\\%')
.replace(/'/g, '%')
.replace(/"/g, "'")
.replace(/[^\\]%/g, function (m) {
return m[0] + '"';
})
.replace('\\%', '%');
First, strings are immutable, any operation on strings like .replace() actually returns a new string. You can NOT do the following:
myString[ i ] = "x";
Your other mistake was using a comparison operator as assignment operator.
myString[ i ] == "x";
Knowing this, you need to construct a new string and replace the value of myString with the new value. One way of constructing a string is using the .split('') method to create an array representation of the string, perform mutations on the array and then revert back to string using the .join('') method of the array.
var myString = " tes't tes\"t tes\"t te'st ";
var tokens = myString.split('');
for (i = 0; i < tokens.length; i++) {
if (tokens[i] == "'") {
tokens[i] = "\"";
continue;
}
if (tokens[i] == "\"") {
tokens[i] = "'";
continue;
}
}
myString = tokens.join('');
console.log(myString);
Besides the incorrect use of == operator, you have another problem in your code:
myString[i] can be used to get the ith character of the string (in most browsers); but it cannot be used to "change" that character. This will work:
var a = myString[i];
This won't:
myString[i] = a;
Here is your code, re-written with minor changes plus the use of charAt and substring to read and change characters of string:
var myString = " tes't tes\"t tes\"t te'st ";
console.log(myString);
for (i = 0; i < myString.length; i++) {
if (myString.charAt(i) == "'") {
myString = myString.substring(0, i) + '"' + myString.substring(i + 1);
} else if (myString.charAt(i) == '"') {
myString = myString.substring(0, i) + "'" + myString.substring(i + 1);
}
}
console.log(myString);
I feel silly asking this because I'm betting the answer is staring right at me but here goes.
I'm taking a string from the CSS style textDecoration and trying to remove the underline portion of the string (and any whitespace around it). It returns true when I run test() but when I do the replace method the string is unaltered. Help?
My code:
textDecoration = function(str) {
var n_str = str + '|/\s' + str + '|/\s' + str + '/\s|' + str + '/\s';
var nre = new RegExp(n_str, "g");
debug_log('Found or not: ' + nre.test(txt));
txt.replace(nre, '');
debug_log('Result: ' + txt);
debug_log('-----------------------');
}
var txt = "underline";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "underline overline line-through";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "overline underline line-through";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
txt = "overline line-through underline";
debug_log('-----------------------');
debug_log('Starting String: ' + txt);
textDecoration("underline");
Output:
replace() returns a new string with the replaces and don't change the actual string. You should do something like:
var newString = txt.replace(nre, '');
debug_log('Result: ' + newString);
test returns a boolean. replace returns a new string. It does not alter the string.
Also, your regular expression is quite odd. Applying str = "underline", you will get:
/underline|\/sunderline|\/sunderline\/s|underline\/s/
which does not match whitespaces, but "/s".