remove spaces in string using javascript - javascript

I need to do some functions on some text field contents before submitting the form, like checking the validity of the customer registeration code, having the customer name as his code in customers table appending an incrementing number.
I don't want to do it after the form is submitted becuase I need it to be displayed in the code field before submitting the form.
My code:
function getCode(){
var temp = document.getElementById("temp").value ;
var d = parseInt(document.getElementById("temp").value) + 1;
document.getElementById("customernumber").value = d;
document.getElementById("code").value = document.getElementById("name").value+"-"+ d;
}
It all works fine, but the last line of code developed the code WITH the spaces between the code.

A couple ways to remove spaces...
Using regex: string.replace(/ /g,'');
Splitting the string by spaces and combining the array with no delimiter:
string.split(' ').join('');

var str = "ab cd ef gh ";
str = str.replace(/\s+/g,"");

Related

How to define a line break in extendscript for Adobe Indesign

I am using extendscript to build some invoices from downloaded plaintext emails (.txt)
At points in the file there are lines of text that look like "Order Number: 123456" and then the line ends. I have a script made from parts I found on this site that finds the end of "Order Number:" in order to get a starting position of a substring. I want to use where the return key was hit to go to the next line as the second index number to finish the substring. To do this, I have another piece of script from the helpful people of this site that makes an array out of the indexes of every instance of a character. I will then use whichever array object is a higher number than the first number for the substring.
It's a bit convoluted, but I'm not great with Javascript yet, and if there is an easier way, I don't know it.
What is the character I need to use to emulate a return key in a txt file in javascript for extendscript for indesign?
Thank you.
I have tried things like \n and \r\n and ^p both with and without quotes around them but none of those seem to show up in the array when I try them.
//Load Email as String
var b = new File("~/Desktop/Test/email.txt");
b.open('r');
var str = "";
while (!b.eof)
str += b.readln();
b.close();
var orderNumberLocation = str.search("Order Number: ") + 14;
var orderNumber = str.substring(orderNumberLocation, ARRAY NUMBER GOES HERE)
var loc = orderNumberLocation.lineNumber
function indexes(source, find) {
var result = [];
for (i = 0; i < source.length; ++i) {
// If you want to search case insensitive use
// if (source.substring(i, i + find.length).toLowerCase() == find) {
if (source.substring(i, i + find.length) == find) {
result.push(i);
}
}
alert(result)
}
indexes(str, NEW PARAGRAPH CHARACTER GOES HERE)
I want all my line breaks to show up as an array of indexes in the variable "result".
Edit: My method of importing stripped all line breaks from the document. Using the code below instead works better. Now \n works.
var file = File("~/Desktop/Test/email.txt", "utf-8");
file.open("r");
var str = file.read();
file.close();
You need to use Regular Expressions. Depending on the fields do you need to search, you'l need to tweek the regular expressions, but I can give you a point. If the fields on the email are separated by new lines, something like that will work:
var str; //your string
var fields = {}
var lookFor = /(Order Number:|Adress:).*?\n/g;
str.replace(lookFor, function(match){
var order = match.split(':');
var field = order[0].replace(/\s/g, '');//remove all spaces
var value = order[1];
fields[field]= value;
})
With (Order Number:|Adress:) you are looking for the fields, you can add more fields separated the by the or character | ,inside the parenthessis. The .*?\n operators matches any character till the first break line appears. The g flag indicates that you want to look for all matches. Then you call str.replace, beacause it allows you to perfom a single task on each match. So, if the separator of the field and the value is a colon ':', then you split the match into an array of two values: ['Order number', 12345], and then, store that matches into an object. That code wil produce:
fields = {
OrderNumber: 12345,
Adresss: "my fake adress 000"
}
Please try \n and \r
Example: indexes(str, "\r");
If i've understood well, wat you need is to str.split():
function indexes(source, find) {
var order;
var result = [];
var orders = source.split('\n'); //returns an array of strings: ["order: 12345", "order:54321", ...]
for (var i = 0, l = orders.length; i < l; i++)
{
order = orders[i];
if (order.match(/find/) != null){
result.push(i)
}
}
return result;
}

Replace string between “variabletext[” and “]” with javascript

I'm trying to build an html form that generates structured JSON code from the input values. This form uses repeat fields.
I have to modify name attributes in cloned fields.
In Javascript I have a string 'menu-item[0][offers][0][price]'.
I would like to replace 'menu-item[0]' with 'menu-item[1]', as in example at http://regexr.com/3gpnt
I'm using RegExp, but is not required.
This is my experiment, but it doesn't work.
var string = 'menu-item[0][offers][price]';
var itemName = 'menu-item';
var regExp = new RegExp(itemName + '\[(.*?)\]', "");
var newString = string.replace(regExp, itemName + '[1]');
console.log(newString);
alert(newString);
Returns 'menu-item[0][offers][price]'.
Test on jsfiddle https://jsfiddle.net/lorenzodetomasi/dmnd7f9L/
Thank you.

How to fetch text using reg exp in 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).

Guide on word occurrence in a textarea

I have a Textarea box, a textbox and a button. I would like on clicking the button, for the word in the textbox to be checked against words in the textarea and count number of occurrence.
I have tried last 2 days to write a click function to do this but not getting anywhere since not sure what codes or logic follows next. Only managed to read the contents in the textarea but not sure how to get the word in the textbox and search against sentence in textarea.
Please I am a newbie in JQuery so not asking for anyone to write the code but more of a guide if possible. If this question isn't permitted here, I am more than happy to delete it. Thanks
Use string.match() along with processing to ensure the first string is not empty and that there actually is a match. Did the following in jQuery since you seemed interested in using it.
var textVal = $('#textbox').val();
var textArea = $('#textarea').val();
var matching = new RegExp('\\b' + textVal + '\\b','g');
var count = textArea.match(matching);
var result = 0;
if (count !== null) {
result = count.length;
}
http://jsfiddle.net/promiseofcake/t8Lg9/3/
You are looking for string occurrences, so take a look at this thread.
You could do this using match(), as suggested in the comments:
var m = searchText.match(new RegExp(wordMatch.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "ig"));
// m.length contains number of matches
But that will also match partial words, like 'fox' in 'foxy'. So another method is to split the input into words and walk over them one by one:
var count = 0;
var words = searchText.split(' ');
for (x in words) {
if (words[x].toLowerCase() == wordMatch) {
count++;
}
}
Take a look at this full example: http://jsfiddle.net/z7vzb/
<input type="text"/>
<textarea>...</textarea>
<button>Get</button>
<div></div>
<script>
$("button").click(function(){
count=$("textarea").text().split($("input[type=text]").val()).length-1;
$("div").html(count);
})
</script>

How do I split a variable length field using html

How do I insert a space/carriage return after a designated number of characters (eight) within a designated html field pulling from a table?
Example:
<ebs:PMLOAD TABLE='DS_CLAIM'><ebs:PMVAL FIELD='DS_CLAIM.CGROUPING_FIELD'></ebs:PMVAL></ebs:PMLOAD>
So if the field contains 12345678910, the output would read:
12345678
910
var arr = string.split(""), output;
arr.splice(8, 0, ' ');
output = arr.join('');
With HTML you don't.
JavaScript is the handler, Using replace method.
str = "1234567890";
alert(str.replace(/^(.{8})(.*)$/mg,'\1 \2'));

Categories

Resources