how to combine regEx expressions - javascript

How do I take each of these and combine them into a single regEx expression?
var t = "<test>";
t = t.replace(/^</, '');
t = t.replace(/>+$/, '');
which results in t equal to test without the <>

You can use pipe |. In regex it means OR:
t = "<test>>".replace(/^<|>+$/g, "");
// "test"
But of course, you can use another ways like:
t = "<test>>".replace(/[<>]/g, "");
// "test"
or even with match:
t = "<test>>".match(/\w+/)[0];
// "test"
Make sure you've added the g-global flag when needed. This flag stands for all occurrences.

If I understand correctly you only want to replace beginning '<' symbols and ending '>' symbols, try this one [>$^<]
var t = "<test>";
t = t.replace('/[>$^<]/', '');

Try this
t = t.replace(/^</, '').replace(/>+$/, '');
If you want it in single line, use | to combine the regex.. Like this
t = t.replace(/^<|>+$/g, "");
or capture groups like this
t = t.replace(/^<(.*)>+$/g, '$1');

Related

JS What's the fastest way to display one specific line of a list?

In my Javascript code, I get one very long line as a string.
This one line only has around 65'000 letters. Example:
config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...
What I have to do is replace all & with an break (\n) first and then pick only the line which starts with "path_of_code=". This line I have to write in a variable.
The part with replace & with an break (\n) I already get it, but the second task I didn't.
var obj = document.getElementById('div_content');
var contentJS= obj.value;
var splittedResult;
splittedResult = contentJS.replace(/&/g, '\n');
What is the fastest way to do it? Please note, the list is usually very long.
It sounds like you want to extract the text after &path_of_code= up until either the end of the string or the next &. That's easily done with a regular expression using a capture group, then using the value of that capture group:
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
}
Live Example:
var theString = "config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
console.log(text);
}
Use combination of String.indexOf() and String.substr()
var contentJS= "123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var index = contentJS.indexOf("&path_of_code"),
substr = contentJS.substr(index+1),
res = substr.substr(0, substr.indexOf("&"));
console.log(res)
but the second task I didn't.
You can use filter() and startsWith()
splittedResult = splittedResult.filter(i => i.startsWith('path_of_code='));

String.replace regex is not replacing `*` in string

I have a string that comes in and I am running a string.replace on it and it is not removing the * character from the string but it is removing the | character.
var s = "|*55.6";
s = s.replace(/[^0-9.]/, "");
console.log(s);
Use a global regular expression (/.../g) if you want to replace more than a single match:
s = s.replace(/[^0-9.]+/g, "") //=> "55.6"
Edit: Following your pattern with + (which matches more than one of a pattern in succession) will produce fewer matches and thus make the replacement with "" run more efficiently than using the g flag alone. I would use them both together. Credit to Jai for using this technique in his answer before me.
Demo Snippet
var s = "|*55.6"
s = s.replace(/[^0-9.]+/g, "")
console.log(s) //=> "55.6"
It's because replace executed just once. Use g option to replace every match.
s = s.replace(/[^0-9.]/g, "");
You haven't used a global flag for your regex, that is why the first occurrence was replaced, than the operation ended.
var s = "|*55.6";
s = s.replace(/[^\d.]/g, "");
console.log(s);
Using + quantifier alone wouldn't help if you have separate occurrences of [^\d.], though would be better to use together with g flag. For example;
var s = "|*55.6a"
s = s.replace(/[^0-9.]+/, "")
console.log(s) //=> "55.6a not OK
You need to use a global (g) flag / modifier or a plus (+) quantifier when replacing the string;
var s = "|*55.6";
s = s.replace(/[^0-9.]/g, "");
console.log(s);
var s = "|*55.6";
s = s.replace(/[^0-9.]+/, "");
console.log(s);
You are missing + to look for one or more occurrences:
var s = "|*55.6";
s = s.replace(/[^0-9.]+/, "");
console.log(s);
Also if you are interested to takeout the numbers, then you can use .match() method:
var s = "|*55.6";
s = s.match(/[(0-9.)]+/g)[0];
console.log(s);
Some answer mentioned the Quantifiers +, but it will still only replace the first match:
console.log("|*45.6abc".replace(/[^0-9.]+/, ""))
If you need to remove all non-digital chars(except .), the modifier/flag g is still required
console.log("|*45.6,34d".replace(/[^0-9.]+/g, ""));

String : Replace function with expression in Javascript

A string representing a currency is to be converted to a number.
For example:
Input : "125.632.454.454.403,51"
Output expected : 125632454454403.51
Currently I am trying:
Trial 1)
a = "125.632.454.454.403,51";
a.replace(/./, '');
Result = "25.632.454.454.403,51"
Trial 2)
a = "125.632.454.454.403,51";
a.replace(/./g, '');
Result = ""
But I expect the replace function to find all the occurrences of "." and replace by "".
Trial 3)
a = "125.632.454.454.403,51";
a.replace(/,/, '');
Result = "125.632.454.454.40351"
I would be glad if I find a fix for this.
You need to use \. instead of .. The dot (.) matches a single character, without caring what that character is. Also you can do it with single replace() with callback .
var str = "125.632.454.454.403,51";
str = str.replace(/\.|,/g, function(m) {
return m == '.' ? '' : '.'
});
document.write(str);
try:
var str = "125.632.454.454.403,51" ;
var result = str.replace(/\./g,'').replace(/\,/g,'.');
console.log(Number(result))
replace returns the changed string, it does not change it in-place!
You can find this out, by refering to the documentation.
Use
var Result = a.split('.').join("");
console.log(Result);
. has specific meaning in a regex. It matches any character. You need to escape the dot if you are actually looking for the character itself
var a = "125.632.454.454.403,51";
var result = a.replace(/\./g,"");
You can also do (parseFloat(a.replace(/[^0-9]+/g,""))/100)
And if you have to do this for multiple currencies, I would recommend looking into autonumeric.js. It handles all this for you.

how to extract string part and ignore number in jquery?

I have a string like foobar1, foobaz2, barbar23, nobar100 I want only foobar, foobaz, barbar, nobar and ignoring the number part.
If you want to strip out things that are digits, a regex can do that for you:
var s = "foobar1";
s = s.replace(/\d/g, "");
alert(s);
// "foobar"
(\d is the regex class for "digit". We're replacing them with nothing.)
Note that as given, it will remove any digit anywhere in the string.
This can be done in JavaScript:
/^[^\d]+/.exec("foobar1")[0]
This will return all characters from the beginning of string until a number is found.
var str = 'foobar1, foobaz2, barbar23, nobar100';
console.log(str.replace(/\d/g, ''));
Find some more information about regular expressions in javascript...
This should do what you want:
var re = /[0-9]*/g;
var newvalue= oldvalue.replace(re,"");
This replaces al numbers in the entire string. If you only want to remove at the end then use this:
var re = /[0-9]*$/g;
I don't know how to do that in JQuery, but in JavaScript you can just use a regular expression string replace.
var yourString = "foobar1, foobaz2, barbar23, nobar100";
var yourStringMinusDigits = yourString.replace(/\d/g,"");

Remove leading comma from a string

I have the following string:
",'first string','more','even more'"
I want to transform this into an Array but obviously this is not valid due to the first comma. How can I remove the first comma from my string and make it a valid Array?
I’d like to end up with something like this:
myArray = ['first string','more','even more']
To remove the first character you would use:
var myOriginalString = ",'first string','more','even more'";
var myString = myOriginalString.substring(1);
I'm not sure this will be the result you're looking for though because you will still need to split it to create an array with it. Maybe something like:
var myString = myOriginalString.substring(1);
var myArray = myString.split(',');
Keep in mind, the ' character will be a part of each string in the split here.
In this specific case (there is always a single character at the start you want to remove) you'll want:
str.substring(1)
However, if you want to be able to detect if the comma is there and remove it if it is, then something like:
if (str[0] == ',') {
str = str.substring(1);
}
One-liner
str = str.replace(/^,/, '');
I'll be back.
var s = ",'first string','more','even more'";
var array = s.split(',').slice(1);
That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.
Assuming the string is called myStr:
// Strip start and end quotation mark and possible initial comma
myStr=myStr.replace(/^,?'/,'').replace(/'$/,'');
// Split stripping quotations
myArray=myStr.split("','");
Note that if a string can be missing in the list without even having its quotation marks present and you want an empty spot in the corresponding location in the array, you'll need to write the splitting manually for a robust solution.
var s = ",'first string','more','even more'";
s.split(/'?,'?/).filter(function(v) { return v; });
Results in:
["first string", "more", "even more'"]
First split with commas possibly surrounded by single quotes,
then filter the non-truthy (empty) parts out.
To turn a string into an array I usually use split()
> var s = ",'first string','more','even more'"
> s.split("','")
[",'first string", "more", "even more'"]
This is almost what you want. Now you just have to strip the first two and the last character:
> s.slice(2, s.length-1)
"first string','more','even more"
> s.slice(2, s.length-2).split("','");
["first string", "more", "even more"]
To extract a substring from a string I usually use slice() but substr() and substring() also do the job.
s=s.substring(1);
I like to keep stuff simple.
You can use directly replace function on javascript with regex or define a help function as in php ltrim(left) and rtrim(right):
1) With replace:
var myArray = ",'first string','more','even more'".replace(/^\s+/, '').split(/'?,?'/);
2) Help functions:
if (!String.prototype.ltrim) String.prototype.ltrim = function() {
return this.replace(/^\s+/, '');
};
if (!String.prototype.rtrim) String.prototype.rtrim = function() {
return this.replace(/\s+$/, '');
};
var myArray = ",'first string','more','even more'".ltrim().split(/'?,?'/).filter(function(el) {return el.length != 0});;
You can do and other things to add parameter to the help function with what you want to replace the char, etc.
this will remove the trailing commas and spaces
var str = ",'first string','more','even more'";
var trim = str.replace(/(^\s*,)|(,\s*$)/g, '');
remove leading or trailing characters:
function trimLeadingTrailing(inputStr, toRemove) {
// use a regex to match toRemove at the start (^)
// and at the end ($) of inputStr
const re = new Regex(`/^${toRemove}|{toRemove}$/`);
return inputStr.replace(re, '');
}

Categories

Resources