JavaScript replace() method not deleting correct lines - javascript

I have a sdp and it has multiple lines. I want to replace one line with " " or remove it. I tried:
obj.sdp = obj.sdp.replace(/a=line5:[\w\W]*\n|\r/gi, "" );
for delete line 5 but it is deleting line 5 and also other lines that comes after line 5. I used \n|\r for delete until here. Also I when I use
sdp = sdp.replace(/a=line5:0.*$/mg, "");
Netbeans give me "Insecure '.' error".

The OR | in your RegExp is excluding a=line5: and therefore when used with the global flag, the \r matches every \r in your String, you probably want
/(a=line5:[^\r\n]*)(?:\r|\n)+/gi
"$1"

I fixed it with;
str.replace(/(a=line5:[\w\W]*?(:\r|\n))/, "" );
Thanks!

Related

How can I remove all white spaces?

I am using the following:
var xpto = "AB23. 3434-.34212 23 42."
I'm removing the "." "-" And ""
xpto.replace(/\./g,"").replace(/\-/g,"").replace("/\s/g","")
How can I remove all white spaces?
Your last replace is using a string, not a regular expression. You also don't seem to have kept the result:
xpto = xpto.replace(/\./g,"").replace(/\-/g,"").replace(/\s/g,"");
// ^ No quotes here -------------------------------^--^
// \--- Remember result
You can also shorten that and just call replace once, using a character class ([...]):
xpto = xpto.replace(/[-.\s]/g,"");
(Note that when using the - character literally in a character class, you must make it the first character after the opening [ or the last character before the closing ], or put a backslash in front of it. If it appears between two other characters ([a-z], for instance), it means "any character in the range".)
You can remove white spaces using replace function
xpto.replace(/\s/g,'');
Your error comes from the quotes around your last regex, however I might also point out that you are calling replace way more than needed:
xpto = xpto.replace(/[\s.-]/g,"");
This will strip out spaces, dots and hyphens.
You done it right, but forgot the quotation marks "" at /\s/g. Also, you want to change the string xpto, to the replaced xpto, so you can now do something with it.
Javascript
var xpto = "AB23. 3434-.34212 23 42."
xpto = xpto.replace(/\./g,"").replace(/\-/g,"").replace(/\s/g,"");
Output
AB233434342122342
JSFiddle demo

preg replace: replace all line breaks outside a title attribute

in general I just want to use a function, which minifies my output (by removing line breaks and tabulators), but the problem is, with a normal code like that
return str_replace(array("\r\n", "\t"), '', $s);
also the title attributes (e.g. when you move over a word and a tooltip appears) are minified and the line breaks get lost. I want to keep line breaks, which are inside a title="textwithlinebreakhere", but remove all line breaks outside.
I have no idea how to realize that, so I hope you can help me.
Thanks!
you should use preg_replace_all() and then use (?<!your_match_here) and its siblings. What do I mean by siblings is negative_lookbehind and positive_lookbehind which conditions your search algorithm to see if a character is after or before a certain letter/sign/digit
Remove undesired characters with trim_all() - PHP :
This function was inspired from PHP's built-in function
trim
that removes undesired characters from the start and end of a string, and in case no such characters a provided as second argument to
trim
, removes white-space characters as provided in this list.
So, what does
trim_all()
do?
trim_all()
was intended to remove all instances of white-spaces from both ends of the string, as well as remove duplicate white-space characters inside the string. But, later on, I made it a general purpose function to do a little more than just white-space trimming and cleaning, and made it to accept characters-to-replace and characters-to-replace-with. With this function, you can:
normalize white-spaces, so that all multiple \r , \n , \t , \r\n , \0 , 0x0b , 0x20
and all control characters can be replaced with a single space, and also trimed from both ends of the string;
remove all undesired characters;
remove duplicates;
replace multiple occurrences of characters with a character or string.
function trim_all( $str , $what = NULL , $with = ' ' )
{
if( $what === NULL )
{
// Character Decimal Use
// "\0" 0 Null Character
// "\t" 9 Tab
// "\n" 10 New line
// "\x0B" 11 Vertical Tab
// "\r" 13 New Line in Mac
// " " 32 Space
$what = "\\x00-\\x20"; //all white-spaces and control chars
}
return trim( preg_replace( "/[".$what."]+/" , $with , $str ) , $what );
}
This function can be helpful when you want to remove unwanted characters from users' input. Here is how to use it.
Example Use :
$full_name = trim_all( $_POST['full_name'] );
or
$full_name = trim_all( $full_name , "\t" , "" );

A regular expression which excludes comments lines starting with "//" in JavaScript

I need to find all lines with string "new qx.ui.form.Button" WHICH EXCLUDE lines starting with comments "//".
Example
line 1:" //btn = new qx.ui.form.Button(plugin.menuName, plugin.menuIcon).set({"
line 2:" btn = new qx.ui.form.Button(plugin.menuName, plugin.menuIcon).set({"
Pattern should catch only "line 2"!
Be aware about leading spaces.
Finally I have to FIND and REPLACE "new qx.ui.form.Button" in all UNCOMMENTED code lines with "this.__getButton".
I tried.
/new.*Button/g
/[^\/]new.*Button/g
and many others without success.
In JavaScript this is a bit icky:
^\s*(?=\S)(?!//)
excludes a comment at the start of a line. So far, so standard. But you cannot look backwards for this pattern because JS doesn't support arbitrary-length lookbehind, so you have to match and replace more than needed:
^(\s*)(?=\S)(?!//)(.*)(new qx\.ui\.form\.Button)
Replace that by
$1$2this.__getButton
Quick PowerShell test:
PS Home:\> $line1 -replace '^(\s*)(?=\S)(?!//)(.*)(new qx\.ui\.form\.Button)','$1$2this.__getButton'
//btn = new qx.ui.form.Button(plugin.menuName, plugin.menuIcon).set({
PS Home:\> $line2 -replace '^(\s*)(?=\S)(?!//)(.*)(new qx\.ui\.form\.Button)','$1$2this.__getButton'
btn = this.__getButton(plugin.menuName, plugin.menuIcon).set({
That being said, why do you care about what's in the commented lines anyway? It's not as if they had any effect on the program.
Ah, if only JavaScript had lookbehinds... Then all you'd need is
/(?<!\/\/.*)new\s+qx\.ui\.form\.Button/g... Ah well.
This'll work just fine too:
.replace(/(.*)new\s(qx\.ui\.form\.Button)/g,function(_,m) {
// note that the second set of parentheses aren't needed
// they are there for readability, especially with the \s there.
if( m.indexOf("//") > -1) {
// line is commented, return as-is
// note that this allows comments in an arbitrary position
// to only allow comments at the start of the line (with optional spaces)
// use if(m.match(/^\s*\/\//))
return _;
}
else {
// uncommented! Perform replacement
return m+"this.__getButton";
}
});
Grep uses Regular Expressions, this will exclude all white space (if any) plus two // at the beginning of any line.
grep -v "^\s*//"

javascript .replace() method not working properly

I am trying to use the replace statement in javascript so that ultimately, i can create an array out of some data that is currently passed in a string.
I have the following javascript:
console.log('data from server:' + server_rule_segements);
//remove trailing ~
server_rule_segements = server_rule_segements.substring(0,server_rule_segements.length-2); // stripping off trailing ~,
console.log("1 - " + server_rule_segements);
server_rule_segements = server_rule_segements.replace("~,,", "~");
console.log("2 - " + server_rule_segements);
Here's the results in the console:
data from server:Home Number,1234,1,no~,,Work Number,12342342,1,no~,,Work Number,12344412341234,1,no~,
1 - Home Number,1234,1,no~,,Work Number,12342342,1,no~,,Work Number,12344412341234,1,no
2 - Home Number,1234,1,no~Work Number,12342342,1,no~,,Work Number,12344412341234,1,no
What I'm wondering is why the replace command didn't replace all the instances of "~,,".
As you can see in the 2nd debug statement, there's still one there.. in what I'm calling "record 2". I'm sure it's something simple that I've missed... but I can't see it right now.
As I test, I changed the code so that I call the replace method twice, like so:
server_rule_segements = server_rule_segements.replace("~,,", "~");
server_rule_segements = server_rule_segements.replace("~,,", "~");
and then it works.
But I don't think I should have to do that.
replace method only replaces first instance, if you want all instances to be replaced use regular expressions. It would be easy because replace method also accepts regular expressions:
server_rule_segements = server_rule_segements.replace(/~,,/g, "~");
would do the trick. Notice the "g" flag means global replace. If you do not want to use regular expressions, use split immediately followed by a join,
server_rule_segements = server_rule_segements.split("~,,").join("~");
String.replace only replaces the first occurance by default.
You need to change server_rule_segements.replace("~,,", "~"); to server_rule_segements.replace(/~,,/g, "~");
change this:
server_rule_segements.replace("~,,", "~")
to
var re = new RegExp("~,,", 'g');
server_rule_segements.replace(re,"~")
Note i didn't run this code

Javascript and regex: remove space after the last word in a string

I have a string like that:
var str = 'aaaaaa, bbbbbb, ccccc, ddddddd, eeeeee ';
My goal is to delete the last space in the string. I would use,
str.split(0,1);
But if there is no space after the last character in the string, this will delete the last character of the string instead.
I would like to use
str.replace("regex",'');
I am beginner in RegEx, any help is appreciated.
Thank you very much.
Do a google search for "javascript trim" and you will find many different solutions.
Here is a simple one:
trimmedstr = str.replace(/\s+$/, '');
When you need to remove all spaces at the end:
str.replace(/\s*$/,'');
When you need to remove one space at the end:
str.replace(/\s?$/,'');
\s means not only space but space-like characters; for example tab.
If you use jQuery, you can use the trim function also:
str = $.trim(str);
But trim removes spaces not only at the end of the string, at the beginning also.
Seems you need a trimRight function. its not available until Javascript 1.8.1. Before that you can use prototyping techniques.
String.prototype.trimRight=function(){return this.replace(/\s+$/,'');}
// Now call it on any string.
var a = "a string ";
a = a.trimRight();
See more on Trim string in JavaScript? And the compatibility list
You can use this code to remove a single trailing space:
.replace(/ $/, "");
To remove all trailing spaces:
.replace(/ +$/, "");
The $ matches the end of input in normal mode (it matches the end of a line in multiline mode).
Try the regex ( +)$ since $ in regex matches the end of the string. This will strip all whitespace from the end of the string.
Some programs have a strip function to do the same, I do not believe the stadard Javascript library has this functionality.
Regex Reference Sheet
Working example:
var str = "Hello World ";
var ans = str.replace(/(^[\s]+|[\s]+$)/g, '');
alert(str.length+" "+ ans.length);
Fast forward to 2021,
The trimEnd() function is meant exactly for this!
It will remove all whitespaces (including spaces, tabs, new line characters) from the end of the string.
According to the official docs, it is supported in every major browser. Only IE is unsupported. (And lets be honest, you shouldn't care about IE given that microsoft itself has dropped support for IE in Aug 2021!)

Categories