How to fetch text using reg exp in javascript - javascript

i need to fetch the text after / from the below code.How to achieve this one.I tried to find '/' location or index value by search() but it didn't worked.The scenario is i need to fetch the text which consists 2 parts as 'Username / some text'. Where user name is dynamic and i need text after the '/'
in HTML it looks like this (for one instance)
<a id="open_0" class="search-result-heading" data-gistname="15b6402d51d897f2ed29" "="" href="http://127.0.0.1:8080/edit.html?notebook=15b6402d51d897f2ed29">tejas1493 / ZZZZ</a>
i able to fetchText for the above but after fetching i need the ' / ZZZZ ' text

Try this one...it might work. output will be ZZZZ.
path = "path of the selector";
var pos = path.lastIndexOf("/");
var name = path.substring(pos+1 , date.length-1);

You can make it without regular expressions with a simple search as you described :
var text = document.getElementById('open_0').innerHtml;
var slash_index = text.search("/");
var first_word = text.substring(0, slash_index);
var second_word = text.substring(slash_index+1);

Running the below code will give you the contents in place of ZZZZ where Z can be a digit, uppercase letter or a lowercase letter.
raw_text = document.getElementById('open_0').innerHTML;
text = raw_text.match(/\/[ ]*[0-9a-zA-Z]+/)[0].match(/[0-9a-zA-Z]+/)[0];
alert(text);
Output: ZZZZ
NOTE: It will show the string all the way to the end of the text within that tag and not just 4 characters (if there are more characters).

Related

Regex to get parts of a string

all i am struggling to get sections of a string with regex without using Split or any other similar function here is my scenario:
I have this text U:BCCNT.3;GOwhich i want to get the different sections divided but the symbols in the middle I have managed to get the first one with this regex /(.+):/.exec(value) this gives me the first word till the colon(:) and these are the different variations of the value
Second section BCCNT
BCCNT.3;GO -> without the U: so the string might also contain no colon so for the second section the logic would be any text that is between : and . or any text ending with . and nothing infront
Third section .3-> any text starting with a . and ending with nothing or anytext staring with a . and ending with a ; semicolon
Fourth section ;GO-> any text starting with a ; and ending with nothing
EDIT
and preferably on separate variables like
const sectionOne = regex.exec(value);
const sectionTwo = regex.exec(value);
const sectionThree = regex.exec(value);
const sectionFour = regex.exec(value);
and which ever value doesnt match the pattern the variable would just be undefined or null or any empty string
Here is a regex approach using 4 separate optional capture groups for each possible component:
var input = "U:BCCNT.3;GO";
var re = /^([^:]+:)?([^.]+)?(\.[^;]+)?(;.*)?$/g;
var m;
m = re.exec(input);
if (m) {
console.log(m[1], m[2], m[3], m[4]);
}
Something like
/^(?:([^:]*):)?([^.]*)\.(?:([^;]*);(.*))?/
For example:
const s = 'U:BCCNT.3;GO';
const m = s.match(/^(?:([^:]*):)?([^.]*)\.(?:([^;]*);(.*))?/);
console.log(m);

Need to extract values from string in Javascript between words and characters

I will be receiving the following string format from an AJAX call:
[link=https://www.w3schools.com text=here]
I need to extract the values after "link=" and the value after "text=" so, my ideal output would assign "https://www.w3schools.com" to a variable and then "here" to a variable as shown in the code below. The values for "link=" and "text=" will change.
I've tried playing around with regex matching and using .split in Javascript, but I can't get the intended values just right.
var str = "[link=https://www.w3schools.com text=here]";
var link = str.match(/link=(.*)/)[1]; //gets the link but includes rest of string
var linkText = str.match(/text=(.*)/)[1]; //gets "here" plus the closing bracket
add "\s" and "]" in your pattern, Try this
var str = "[link=https://www.w3schools.com text=here]";
var link = str.match(/link=(.*)\s/)[1]; //gets the link but includes rest of string
var linkText = str.match(/text=(.*)]/)[1];
console.log(link);
console.log(linkText);
You may use
var str = "[link=https://www.w3schools.com text=here]";
var m, res=[], rx=/(?:^|[\s[])(link|text)=([^\][\s]*)/g;
while (m = rx.exec(str)) {
console.log(m[1], "=", m[2]);
}
The regex is
/(?:^|[\s[])(link|text)=([^\][\s]*)/
See the regex demo.
Details
(?:^|[\s[]) - start of string or a whitespace or [
(link|text) - Group 1: link or text words
= - a = symbol
([^\][\s]*) - Group 2: any 0+ chars other than [, ] and whitespace.

replace 2 different sets of words in a string in javascript

so I need to replace 2 sets of words in a string; the title of the web page. However, I seem to be able to get one set of words to be removed.
The title is being created by wordpress, which is adding words at the start and end of the title which I don't want to be displayed (as I am calling the title, using PHP, to dynamically create a few bits of information on the page, which are subject to change)
The code I have so far is:
<script>
var str = document.title.replace(/ - CompanyName/i, '');
document.write(str);
</script>
However, I need something which is basically:
var str = document.title.replace(/ - CompanyName/i, '') && document.title.replace(/The /i, '');
This is because the title will produce itself like "The PAGETITLE - CompanyName"
Any ideas how to remove 2 sections of the same string?
Keep the title in a separate variable, re-assign the variable with the result of each replace, set the document title:
var title = "The PAGETITLE - CompanyName";
title = title.replace("The ", "");
title = title.replace(" - CompanyName", "");
document.title = title;
Or, if you like one-liners:
document.title = document.title.replace("The ", "").replace(" - CompanyName", "");
you can directly use like this
var title = "The PAGETITLE - CompanyName";
title.replace(/The(.*?)-[^-]*/,'$1')
var str = document.title.replace(/ - CompanyName/i, '').replace(/The
/i, '');
the replace function yields the new string, which you want to run through replace again.
You can chain functions in JQuery like this:
var str = document.title.replace(/ - CompanyName/i, '').replace(/The /i, '');

How can I find a specific string and replace based on character?

I'm trying to find a specific character, for example '?' and then remove all text behind the char until I hit a whitespace.
So that:
var string = '?What is going on here?';
Then the new string would be: 'is going on here';
I have been using this:
var mod_content = content.substring(content.indexOf(' ') + 1);
But this is not valid anymore, since the specific string also can be in the middle of a string also.
I haven't really tried anything but this. I have no idea at all how to do it.
use:
string = string.replace(/\?\S*\s+/g, '');
Update:
If want to remove the last ? too, then use
string = string.replace(/\?\S*\s*/g, '');
var firstBit = str.split("?");
var bityouWant = firstBit.substring(firstBit.indexOf(' ') + 1);

How to detect line breaks in a text area input?

What is the best way to check the text area value for line breaks and then calculate the number of occurrences, if any?
I have a text area on a form on my webpage. I am using JavaScript to grab the value of the text area and then checking its length.
Example
enteredText = textareaVariableName.val();
characterCount = enteredText.length; // One line break entered returns 1
If a user enters a line break in the text area my calculation above gives the line break a length of 1. However I need to give line breaks a length of 2. Therefore I need to check for line breaks and the number of occurrences and then add this onto the total length.
Example of what I want to achieve
enteredText = textareaVariableName.val();
characterCount = enteredText.length + numberOfLineBreaks;
My solution before asking this question was the following:
enteredText = textareaVariableName.val();
enteredTextEncoded = escape(enteredText);
linebreaks = enteredTextEncoded.match(/%0A/g);
(linebreaks != null) ? numberOfLineBreaks = linebreaks.length : numberOfLineBreaks = 0;
I could see that encoding the text and checking for %0A was a bit long-winded, so I was after some better solutions. Thank you for all the suggestions.
You can use match on the string containing the line breaks, and the number of elements in that array should correspond to the number of line breaks.
enteredText = textareaVariableName.val();
numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
characterCount = enteredText.length + numberOfLineBreaks;
/\n/g is a regular expression meaning 'look for the character \n (line break), and do it globally (across the whole string).
The ||[] part is just in case there are no line breaks. Match will return null, so we test the length of an empty array instead to avoid errors.
Here's one way:
var count = text.length + text.replace(/[^\n]/g, '').length;
Alternatively, you could replace all the "naked" \n characters with \r\n and then use the overall length.
I'd do this using a regular expression:
var inTxt = document.getElementById('txtAreaId').value;
var charCount = inTxt.length + inTxt.match(/\n/gm).length;
where /\n/ matches linebreaks (obviously), g is the global flag. m stands for mult-line, which you evidently need in this case...Alternatively, though as I recall this is a tad slower:
var charCount = inTxt.length + (inTxt.split("\n").length);
Edit
Just realized that, if no line breaks are matched, this will spit an error, so best do:
charCount = intTxt.length + (inTxt.match(/\n/) !== null ? inTxt.match(/\n/gm).length : 0);
Or something similar...
For new JS use encodeURI(), because escape() is deprecated in ECMAScript 1.5.
Instead use:
enteredText = textareaVariableName.val();
enteredTextEncoded = encodeURI(enteredText);
linebreaks = enteredTextEncoded.match(/%0A/g);
(linebreaks != null) ? numberOfLineBreaks = linebreaks.length : numberOfLineBreaks = 0;
You can split the text based on new lines:
let textArray = text.split(/^/gm)
console.log(textArray.length)

Categories

Resources