javascript regular expression ignore condition between the text - javascript

I have a text for example as below:
"head1>data1,data2,data3|head2>data1,data2,data3|head3>data3,data4,data5**
now I want to replace ">data1..|" with "|"
I am using this: ".replace(/>\S+\||>\S+$/g,"|");"
But this is not helping as it gives me data as below:
"head1|head3|" instead of "head1|head2|head3|"
I am unable to find the right method.

You can use
>\S+?(?:\||$)
See the regex demo
The point is to make \S+ lazy, and to shorten the pattern we can use place the >\S+? before the alternation group.
Pattern details:
>\S+? - a literal > followed with 1+ non-whitespace symbols but as few as possible up to
(?:\||$) - a literal | or the end of string.

A simple approach :), was trying like this
var str = "head1>data1,data2,data3|head2>data1,data2,data3|head3>data3,data4,data5";
console.log(str.replace(/>[a-z1-9,]+/g,"|").replace(/\|+/g, "|"));
>[a-z1-9,]+ will select >data1,data2,data3
and then replaced multiple | with single |
:)

You can use:
>[a-z0-9,]+\|
and then replace this with single | every time.

Related

How to replace & and space from a string Angular

I am trying to replace '&' and 'space' from a string.
I can remove the space by string.replace(/[\s]/g, '');
and remove the special character & by string.replace(/[^\da-zA-Z]/g, '')
Can I use both regex in one code? for removing special charecters and space from the string.
Use | to "or" regexes, e.g.
/(\s|&)/g
Grouping via (...) can be necessary to scope what gets or'd.
In this case, you just have two selectors, so it should work without as well.
/\s|&/g
Combine regex for & and space /[& ]+/g
var str='abzx12& 1'
console.log(str.replace(/[& ]+/g,''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here you go with one more solution
.replace(/ |&/g,'')
Example
var a = "asdasdas dsadasdas dasdas asdas & dasdasd &&&&";
console.log(a.replace(/ |&/g,''));
Try this if you don't want to use regex.
var str = "abc def & ghi jkl & mno";
console.log(str.split(' ').join('').split('&').join(''));
first replace space with null and than replace '&' with null.
It might be help you.

can i improve this "regex"?

I have the following string:
const myString = '"{{ some text here }}"'
I want to remove the quotes before {{ and after }}. I can do:
myString.replace('"{{', '{{').replace('}}"', '}}')
But I'm wondering if there is a better way to achieve this without calling replace twice?
Does anyone can let me know if there is a better way and explain?
http://jsbin.com/xafovamihi/edit?js,console
You may use a regex with an alternation group where you can capture {{ and }} into Group 1 and 2 respectively and replace with the backreferences only:
var myString = '"{{ some text here }}"';
console.log(myString.replace(/"({{)|(}})"/g, '$1$2'))
Details:
"({{) - matches " and captures {{ into Group 1
| - or
(}})" - captures }} into Group 2 and matches "
Since the replacement backreferences, when referencing a group that did not participate in the match, are initialized with an empty string, this $1$2 replacement will work properly all the time.
The global modifier /g will ensure all matches are replaced.
An easy way would be to combine the two patterns into one match using regex OR, so you get /"{{|}}"/g
Why not to use regex to find {{ with }} and any text between?
const myString = '"{{ some text here }}"',
reg = /{{.*?}}/;
console.log(myString.match(reg)[0]);

Using a split with a regex not replacing correctly?

I'm trying to parse rows of text in order to retrive the 4 version numbers:
v.1.7.600.0 - latest | 9.2.6200.0 to 9.2.9999
I'm looking to be able to parse a line like this into:
['v.1.7.600.0', 'latest', '9.2.6200.0', '9.2.9999']
At the moment, I have something like this:
var line = "v.1.7.600.0 - latest | 9.2.6200.0 to 9.2.9999"
var result = line.split(/ (\||-|to) /g)
console.log(result)
I'm not that great at regex but it matches so i'm not sure why it includes them in the result.
You are almost there, just use a non-capturing group:
var line = "v.1.7.600.0 - latest | 9.2.6200.0 to 9.2.9999";
var result = line.split(/\s+(?:\||-|to)\s+/);
console.log(result);
You need a non-capturing group because split() will extract captured values into the resulting array.
Also, it might be more convenient to match one or more whitespaces with \s+ rather than using a literal space.
Besides, the /g modifier is redundant with split(), it the default behavior.
You also may define a character class for single char delimiters, and write a bit more compact /\s+(?:[|-]|to)\s+/ regex.

How to extract a particular text from url in JavaScript

I have a url like http://www.somedotcom.com/all/~childrens-day/pr?sid=all.
I want to extract childrens-day. How to get that? Right now I am doing it like this
url = "http://www.somedotcom.com/all/~childrens-day/pr?sid=all"
url.match('~.+\/');
But what I am getting is ["~childrens-day/"].
Is there a (definitely there would be) short and sweet way to get the above text without ["~ and /"] i.e just childrens-day.
Thanks
You could use a negated character class and a capture group ( ) and refer to capture group #1. The caret (^) inside of a character class [ ] is considered the negation operator.
var url = "http://www.somedotcom.com/all/~childrens-day/pr?sid=all";
var result = url.match(/~([^~]+)\//);
console.log(result[1]); // "childrens-day"
See Working demo
Note: If you have many url's inside of a string you may want to add the ? quantifier for a non greedy match.
var result = url.match(/~([^~]+?)\//);
Like so:
var url = "http://www.somedotcom.com/all/~childrens-day/pr?sid=all"
var matches = url.match(/~(.+?)\//);
console.log(matches[1]);
Working example: http://regex101.com/r/xU4nZ6
Note that your regular expression wasn't actually properly delimited either, not sure how you got the result you did.
Use non-capturing groups with a captured group then access the [1] element of the matches array:
(?:~)(.+)(?:/)
Keep in mind that you will need to escape your / if using it also as your RegEx delimiter.
Yes, it is.
url = "http://www.somedotcom.com/all/~childrens-day/pr?sid=all";
url.match('~(.+)\/')[1];
Just wrap what you need into parenteses group. No more modifications into your code is needed.
References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
You could just do a string replace.
url.replace('~', '');
url.replace('/', '');
http://www.w3schools.com/jsref/jsref_replace.asp

Split each string from any given paragraph in javascript

I have a textArea. I am trying to split each string from a paragraph, which has proper grammar based punctuation delimiters like ,.!? or more if any.
I am trying to achieve this using Javascript. I am trying to get all such strings in that using the regular expression as in this answer
But here, in javascript for me it's not working. Here's my code snippet for more clarity
$('#split').click(function(){
var textAreaContent = $('#textArea').val();
//split the string i.e.., textArea content
var splittedArray = textAreaContent.split("\\W+");
alert("Splitted Array is "+splittedArray);
var lengthOfsplittedArray = splittedArray.length;
alert('lengthOfText '+lengthOfsplittedArray);
});
Since its unable to split, its always showing length as 1. What could be the apt regular expression here.
The regular expression shouldn't differ between Java and JavaScript, but the .split() method in Java accepts a regular expression string. If you want to use a regular expression in JavaScript, you need to create one...like so:
.split(/\W+/)
DEMO: http://jsfiddle.net/s3B5J/
Notice the / and / to create a regular expression literal. The Java version needed two "\" because it was enclosed in a string.
Reference:
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
You can try this
textAreaContent.split(/\W+/);
\W+ : Matches any character that is not a word character (alphanumeric & underscore).
so it counts except alphanumerics and underscore! if you dont need to split " " (space) then you can use;
var splittedArray = textAreaContent.split("/\n+/");

Categories