Javascript string remove line if not includes - javascript

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);

Related

Regex poor performance when nothing matches

I have a problem with slow working regex, but only in case when the patter doesn't match. In all other cases performance are acceptable, even if patter matches in the end of text. I'am testing performance on 100KB text input.
What I am trying to do is to convert input in HTML-like syntax which is using [] instead of <> brackets and translate it to valid XML.
Sample input:
...some content[vc_row param="test1"][vc_column]text [brackets in text] content[/vc_column][/vc_row][vc_row param="xxx"]text content[/vc_row]...some more content
Sample output:
...some content<div class="vc_row" param="test1"><div class="vc_column" >text [brackets in text] content</div></div><div class="vc_row" param="xxx">text content</div>...some more content
To do this I am using regex:
/(.*)(\[\/?vc_column|\[\/?vc_row)( ?)(.*?)(\])(.*)/
And I do this in while loop until the patter matches.
As I mentioned before this works, but last iteration is extremly slow (or first if nothing matches). Here is complete javascript I am using:
var str = '...some content[vc_row param="test1"][vc_column]text content[/vc_column][/vc_row][vc_row param="xxx"]text content[/vc_row]...some more content';
var regex = /(.*)(\[\/?vc_column|\[\/?vc_row)( ?)(.*?)(\])(.*)/;
while (matches = str.match(regex)) {
matches = str.match(regex);
if (matches[2].slice(1, 2) !== '/')
str = matches[1] + "<div class=\"" + matches[2].slice(1) + "\"" + " " + matches[4] + ">" + matches[6];
else
str = matches[1] + "</div>" + matches[6];
}
How could i improve my regex "not match" performance?
You can split it up in 2 regex.
One for the start tags, one for the closing tags.
And then chain 2 global g replaces.
var str = '...some content[vc_row param="test1"][vc_column]text with [brackets in text] content[/vc_column][/vc_row][vc_row param="xxx"]text content[/vc_row]...some more content';
const reg1 = /\[(vc_(?:column|row))(\s+[^\]]+)?\s*\]/g;
const reg2 = /\[\/(vc_(?:column|row))\s*\]/g;
var result = str.replace(reg1, "<div class=\"$1\"$2>").replace(reg2, "</div>");
console.log(result);
Note that those (.*) in the original regex aren't needed this way.
Using a nameless function, then it could be done via 1 regex replace.
var str = '...some content[vc_row param="test1"][vc_column]text with [brackets in text] content[/vc_column][/vc_row][vc_row param="xxx"]text content[/vc_row]...some more content';
const reg = /\[(\/)?(vc_(?:column|row))(\s+[^\]]+)?\s*\]/g;
var result = str.replace(reg, function(m,c1,c2,c3){
if(c1) return "</div>";
else return "<div class=\""+ c2 +"\""+ (c3?c3:"") +">";
});
console.log(result);
How about a replace... Like
str.replace(/\[(\/?)(vc_column|vc_row)([^\]]*?)\]/g, function(a,b,c,d) {
return '<' + b + 'div' + (b==='/' ? '' : ' class="' + c + '"') + d + '>';
});
This matches a tag (start or end) and all attributes, including brackets, capturing everything except the brackets. Then puts it back together in the correct format (divs with classes).
And the global flag (/../g) removes the need for any loops.
var sInput = '...some content[vc_row param="test1"][vc_column]text [brackets in text] content[/vc_column][/vc_row][vc_row param="xxx"]text content[/vc_row]...some more content';
console.log(sInput.replace(/\[(\/?)(vc_column|vc_row)([^\]]*?)\]/g, function(a,b,c,d) {
return '<' + b + 'div' + (b==='/' ? '' : ' class="' + c + '"') + d + '>';
})
);

Removing a string within a string using JavaScript

I am having a string like this:
"welcome country !
and some texts
Keyword1:the value
keyword2: the value2"
I want to remove keyword on undo the corresponding checkbox and also its value using Javascript. Now i could remove the keyword while undo checkbox but not the value they have entered near the keyword.
I have tried substring functions and some other, but i couldn't fix it.
my code below:
$("#txtNote").val(url.replace($(this).attr("data-id") + ":", ""));
I just want to remove the texts immediately after the ":"
here is my entire code:
if ($(this).attr("data-selected1") == "true") {
$("#detailChronic").show();
$(this).attr("data-selected1", "false");
//$(".hjk").remove(":contains('" + $(this).attr("data-id") + "')");
var url = $.trim($("#txtNote").val());
str = $("#txtNote").val();
//var t = str.substring(str.indexOf(":"))
//alert(t);
//url = url.replace(/\s+/g, "\n");
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":", ""));
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":" + $(this).attr("data-id").value(), ""));
//url.replace($(this).attr("data-id") + ":", "");
alert(url);
var temp2 = temp1.replace(/($(this).attr("data-id"))(\:(.*))/, "");
alert(temp2);
var temp1 = url.replace($(this).attr("data-id"), "");
alert(temp1);
$("#txtNote").val(temp1);
// $("#txtNote").val(url.replace($(this).attr("data-id") + ":" + $(this).attr("data-id").value(), ""));
if ($("#selectedList").html() == "") {
$("#detailChronic").hide();
}
}
if you want to remove 'Keyword1:the value', then try
var keyWordToRemove = 'Keyword1';
var rgxStr = keyWordToRemove + ':[a-zA-Z0-9 ]*\n';
var rgx = new RegExp(rgxStr,'g');
var text = `welcome country !
and some texts
Keyword1:the value
keyword2: the value2`;
console.log(text);
text = text.replace(rgx,"");
console.log(text);
Hope it helps :)
You can try it using regex like this
var url = `welcome country !
and some texts
Keyword1:the value
keyword2: the value2`;
console.log(url.replace("Keyword1:", "test key "))
console.log(url.replace(/(Keyword1)(\:(.*))/, "$1 test value"))
you can replace Keyword1 with $(this).attr("data-id") + ":" in your code

Difficulty implementing Equals Operator

I have two Parse generated objectId strings that I know are equal, because I print them out and read them, and they are the same.
They are requestedUserId and requestingUserId.
I have tried as mentioned in the comments to check for invisible characters
console.log('"' + requestedUserId + '"')
console.log('"' + requestingUserId + '"')
However, as suspected, they print out equal.
The code below never runs, it jumps to the else statement. Is there a problem with my logic, or anything else that is readily apparent?
Parse.Cloud.beforeSave("FriendRequest", function(request, response) {
var requestedUserId = request.object.get("to")
var requestingUserId = request.object.get("from")
console.log('"' + requestedUserId + '"')
console.log('"' + requestingUserId + '"')
// One cannot request oneself
if (requestedUserId == requestingUserId) {
console.log("can't send a request to yourself")
response.error("can't send a request to yourself");
} else {
(...)
}
});
As per my comment, I suggest that you check the length of the 2 strings rather than relying on visibility in your console.
var str1 = 'abc123';
var str2 = 'abc123' + String.fromCharCode(0);
console.log('"' + str1 + '"', str1.length);
console.log('"' + str2 + '"', str2.length);
console.log(str1 == str2);

How can I remove extra white space in a string in JavaScript?

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

Why won't replace work with my regex object when test does?

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".

Categories