I have a textarea where the user will enter multi-line input text and I want to go through it line by line and looking for specific keywords. Once the keyword is found, I want to extract from that keyword until the end of the line (i.e. new line reached).
I have the following code but it only extracts Sender: as output when the alert is executed. I am not really familiar with JavaScript so would really appreciate a better elegant approach than this.
function processFunction() {
var lines = document.getElementById("textarea").value.split('\n');
for(var i = 0;i < lines.length;i++){
extractSenderIP(lines[i]);
}
}
function extractSenderIP(someText) {
var re = new RegExp( "Sender:", "g" );
var result = re.exec(someText);
alert(result);
}
Your regex is only looking for the word "Sender:". You would need to tell it to find Sender: followed by anything to the next new line char:
var re = new RegExp( "Sender:.*\n", "g" );
At that point, you dont really even need to iterate around lines. The global regex should find all instances and return them in a collection.
Since you already split by newline split('\n'), you can check in your loop if your keyword matches and then get the line like this:
Sender:.*
Match Sender:
Match any character zero or more times .*
As an example:
function processFunction() {
var lines = document.getElementById("textarea").value.split('\n');
for(var i = 0;i < lines.length;i++){
extractSenderIP(lines[i]);
}
}
function extractSenderIP(someText) {
var re = new RegExp("Sender:.*", "g" );
var result = re.exec(someText);
if (result && result[0]) {
console.log(result[0]);
}
}
processFunction();
<textarea rows="4" cols="50" id="textarea">
Sender:test1
Sender:test1 Sender:test2
Sender: test2
test3</textarea>
re.exec returns an object with an index attribute, so you could do something like this:
result = re.exec(someText);
alert(someText.substring(result.index))
Related
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
i have a multiline textfield("Adressfeld"), and i want to Uppercase every first letter and LowerCase the rest of every single word in this text area.
Here is my try:
function capitalize(Eingabe){
Eingabe = this.getField("Adressfeld").value;
var strArr = Eingabe.split(" ");
var newArr = [];
for(var i = 0 ; i < strArr.length ; i++ ){
var FirstLetter = strArr[i].charAt(0).toUpperCase();
var restOfWord = strArr[i].slice(1).toLowerCAse();
newArr[i] = FirstLetter + restOfWord;
}
return newArr.join(' ');
}
Ausgabe = this.getField("Empfängername");
Ausgabe.value = capitalize();
With the script shown above, every single word in the first line of the text area is capitalized. But in every other line, the first word isn't capitalized.
How i have to change the script to get it work?
Thanks,
I have included an example below try like that, it will solve your problem
Html
<input type="button" value="clk" onclick="z();"/>
<textarea rows="4" id="text" cols="50">
JS
function z()
{
var z=document.getElementById("text").value;
var x=z.replace(/\b./g, function(m){ return m.toUpperCase(); });
alert(x);
}
DEMO
I you want to Convert Every first letter of each word to upper and all other letters are lower then first convert the entire string to lowercase.Then do the same things as above.
DEMO2
Meinst du sowas?
var textToArray = document.getElementById('myTextarea').value.split('\n');
/* Hier eine Schleife zur Bearbeitung von textToArray */
var arrayToString = textToArray.join(' ');
The split operation fails -- the result of the first split cannot be split again on another character.
I see no reason to first replace returns by a single type \n and then try to split on either \n or a space. It's way easier to just replace the returns by a single space and only then split:
var strArr = String(Eingabe.value).replace(/[\r\n]+/g," ").split(" ");
With that, the rest seems to work.
Here is another approach, which may or may not work as well (it depends on whether Javascript's interpretation of "word boundary" \b agrees with your own):
function capitalize(Eingabe){
// Eingabe = this.getField("Adressfeld");
var strArr = String(Eingabe.value).replace(/[\r\n ]+/g,' ');
strArr = strArr.replace (/\b[a-z]/g, function(found) { return found.toUpperCase(); });
return strArr;
}
A few things:
• The argument of the function is Eingabe. In this case, this is a variable containing a value, and it does not make sense at all to redefine in the first line of the function. The way the function looks like, you won't need an argument, and therefore, your function definition looks like this:
function capitalize() {
• That done, define Eingabe properly as var Eingabe .
• With the array, you essentially want to create a two-dimensional array. First create the array of lines and then a loop through the lines, as it has been suggested in the answer by #Entimon
• You end with
this.getField("Adressfeld").value = capitalize() ;
And that should do it.
thanks for your help!
The correct answer is based on Arunprasanth KV's jsfiddle.net/svh1jd99
function capitalize()
{
var capitalize = this.getField("Adressfeld").value;
var done = capitalize.replace(/\b./g, function(m){ return m.toUpperCase();});
return done;
};
this.getField("Adressfeld").value = capitalize();
Thanks again for your help.
By using jQuery you can do this as shown below:
Demo: https://jsfiddle.net/cxow8198/3/
<input type="text" id="input">
<script>
//usage
$("input").keyup(function() {
toUpper(this);
});
//function
function toUpper(obj) {
var mystring = obj.value;
var sp = mystring.split(' ');
var wl=0;
var f ,r;
var word = new Array();
for (i = 0 ; i < sp.length ; i ++ ) {
f = sp[i].substring(0,1).toUpperCase();
r = sp[i].substring(1).toLowerCase();
word[i] = f+r;
}
newstring = word.join(' ');
obj.value = newstring;
return true;
}
</script>
Query code snippet to make capitals of the first letter of every word in the string. This could be used to prevent users from entering all caps for titles or text when they input data into forms.
I have a string which I need to separate correctly:
self.view.frame.size.height = 44
I need to get only view, frame, size, and height. And I need to do it with a regular expression.
So far I've tried a lot of variants, none of them are even close to what I want to get. And my code now looks like this:
var testString = 'self.view.frame.size.height = 44'
var re = new RegExp('\\.(.*)\\.', "g")
var array = re.exec(testString);
console.log('Array length is ' + array.length)
for (var i = 0; i < array.length; i++) {
console.log('<' + array[i] + ">");
}
And it doesn't work at all:
Array length is 2
<.view.frame.size.>
<view.frame.size>
I'm new at Javascript, so maybe I want the impossible, let me know.
Thanks.
In Javascript, executing a regexp with the g modifier doesn't return all the matches at once. You have to execute it repeatedly on the same input string, and each one returns the next match.
You also need to change the regexp so it only returns one word at a time. .* is greedy, so it returns the longest possible match, so it was returning all the words between the first and last .. [^.]* will match a sequence of non-dot characters, so it will just return one word. You can't include the second . in the regexp, because that will interfere with the repetition -- each repetition starts searching after the end of the previous match, and there's no beginning . after the ending . of the word. Also, there's no . after height, so the last word won't match it.
EDIT: I've changed the regexp to use \w* instead of [^.]*, because it was grabbing the whole height = 44 string instead of just height.
var testString = 'self.view.frame.size.height = 44';
var re = /\.(\w*)/g;
var array = [];
var result;
while (result = re.exec(testString)) {
array.push(result[1]);
}
console.log('Array length is ' + array.length)
for (var i = 0; i < array.length; i++) {
console.log('<' + array[i] + ">");
}
If you're sure that your data will be always in the same format you can use this:
function parse (string) {
return string.split(" = ").shift().split(".").splice(1);
}
In your context, split is a MUCH better option:
var str = "self.view.frame.size.height = 44";
var bits1 = str.split(" ")[0];
var bits2 = bits1.split(".");
bits2.shift(); // get rid of the unwanted self
console.log(bits2);
A have a string that can reach up to 100 characters in lenght. Is there an easy way to insert line breaks in the word every 10th letter? For example:
aaaaaaaaaaaaaaaaaaaaaaaaa
Should turn in to
aaaaaaaaaa<br/>aaaaaaaaaa<br/>aaaaa
I know that i can modify html with the html() method, but im not sure how to count characters and insert the tags. Thanks
Here is one option:
string.match(/.{1,10}/g).join("<br/>");
Assuming the text is inside a div or a span:
<div id="myDiv">aaaaaaaaaaaaaaaaaaaaaaaaa</div>
You can do:
$(function() {
var html=$('#myDiv').html();
var newHtml='';
for (var i=0;i<html.length;i++) {
newHtml=newHtml+html[i];
if ((i+1)%10==0) {newHtml=newHtml+'<br/>';}
}
$('#myDiv').html(newHtml);
});
Here is example: http://jsfiddle.net/68PvB/
Good Luck!
If you have your string in a variable you can use its replace method like this:
var chunklen = 2; //the length of the chunks you require
var str = '123456789'; //your string
var rxp = new RegExp( '(.{'+chunklen+'})', 'g' );
var str2 = str.replace( rxp, '$1<br/>' );
console.log( str2 ); //12<br/>34<br/>56<br/>78<br/>9
I'm almost there! Just can't figure out the last part of what I need... forming the array.
I want to go through an html file and extract url's from between the phrases playVideo(' and ')
For testing purposes I am just trying to get it to work on the variable str, eventually this will be replaced by the html document:
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match("playVideo\\(\'(.*?)\'");
alert(testRE[1]);
</script>
This will output 'url1' but if I change it to alert(testRE[2]) it is undefined. How can I get it to fill out the array with all of the URLs (eg testRE[2] output 'url2' and so on) ?
Thanks for any help, new to regex.
Cannot comment, why is that, but adding that by iterating on the regex you get access to the groups;
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var re = /playVideo\('(.*?)'\)/g;
while (match = re.exec(str)) {
alert(match[1]);
}
Normally a javascript regular expression will just perform the first match. Update your regular expression to add the g modifier. Unfortunately JavaScript regular expressions don't have a non-capturing group so you have to do a little more processing to extract the bit you want e.g.
<script type="text/javascript">
var str ="playVideo('url1') BREAK playVideo('url2') BREAK playVideo('url3')";
var testRE = str.match(/playVideo\(\'[^']*\'/g);
var urls = [];
for (var i = 0; i < testRE.length; i++)
{
urls[i] = testRE[i].substring(11).match(/[^']*/);
}
alert(urls[1]);
alert(urls[2]);
</script>