I have set of numbers from an excel like this
05143
05250
05252
05156
05143
05441
05143
05031
05050
05101
05821
05822
05861
and after every 5th digit I wanted to add a ,
My problem is that after every 5th digit it considers a white space carriage as a digit and then split the items such as
05143 ↵0525 0↵052 50↵05 and so on...
and that's why , split is breaking. I tried to replace it as item.replace(/↵/g, ""); but its not working.
here is my code
item.replace(/↵/g, "")
console.log(item)
if(item.length > 5){
for (var i = 0; i < item.length; i += 5) {
chunks.push(item.substring(i, i + 5));
}
console.log(chunks)
var tempItem;
chunks.forEach(function(item2) {
if (tempItem == undefined) {
tempItem = "'" + item2 + "'";
} else {
tempItem = tempItem + ",'" + item2 + "'";
}
})
It's not clear from the question what character code you have in your string that cause the problem.
But I think that if you use this general replace you will solve.
item.replace(/\W/g, '')
it works when we write it as
item.split('\n')
Related
I need to write a function in javascript, which finds a string in a text and prints how many times the string is found in the text. Here is my code, It's not working for some reason.... Please help
var word = 'text',
text = 'This is some wierd stupid text to show you the stupid text without meaning text just wierd text oh text stupid text without meaning.';
searchWord(word, text);
function searchWord(word, text) {
switch (arguments.length) {
case 1: console.log('Invalid input, please try again'); break;
case 2: var array = text.split(' ');
for (var i = 0; i < array.length; i++) {
var count = 0;
if (array[i] === word) {
count ++;
}
}
console.log('Word ' + word + ' is repeated in the text ' + count + ' times');
}
}
There is a small problem in your code. You have to move
var count = 0;
outside the for loop.
Move
var count = 0;
Outside your loop
Your count variable should be outside of your for loop, else you are resetting it everytime you enter the loop.
function searchWord(word, text) {
switch (arguments.length) {
case 1: console.log('Invalid input, please try again'); break;
case 2: var array = text.split(' ');
var count = 0;//Place it here.
for (var i = 0; i < array.length; i++) {
if (array[i] === word) {
count ++;
}
}
console.log('Word ' + word + ' is repeated in the text ' + count + ' times');
}
}
You could just use a regular expression to count the occurences
var word = 'text',
text = 'This is some wierd stupid text to show you the stupid text without meaning text just wierd text oh text stupid text without meaning.';
searchWord(word, text);
function searchWord(word, text) {
var re = new RegExp(""+text+"", "g");
var count = (text.match(/text/g) || []).length;
console.log('Word ' + word + ' is repeated in the text ' + count + ' times');
}
Already answered but this is a short version of getting the count:
function getWordCount(word, text) {
if(arguments.length === 0) return;
var count = 0;
text.split(" ").forEach(function(val) {
if(val === word) count++;
});
}
A simple one line solution without loops or RegExp
This one line solution appears to work. Note that it appends a space to the head and tail of the sentence to catch matching words at ends. This could be done with a pure RegExp too, but then it wouldn't be one line ... and I like simple solutions.
return (' ' + text.toLowerCase() + ' ').split( ' ' + word.toLowerCase() + ' ' ).length - 1;
And refactoring the original code we can eliminate 10 extraneous lines and a loop:
function searchWord(word, text) {
return (' ' + text.toLowerCase() + ' ').split( ' ' + word.toLowerCase() + ' ' ).length - 1;
}
var word = 'text',
text = 'This is some wierd stupid text to show you the stupid text without meaning text just wierd text oh text stupid text without meaning.';
console.log('Word ' + word + ' is repeated in the text ' + searchWord(word,text) + ' times');
I want to have a user's input auto fill the punctuation of a phone number to look like this (xxx) xxx-xxxx. I have written an example jfiddle here but it breaks when filling in the last 4 digits of the phone number.
$("#phone").on("change keyup paste", function () {
var output;
var input = $("#phone").val();
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 4);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$("#phone").val(output);
});
HTMl:
<input id='phone'></input>
I realize this post is older but i found it quite useful and made some minor modifications to enhance it for all telephone fields and to allow for deleting characters if the user makes a mistake.
$("input[type='tel']").each(function(){
$(this).on("change keyup paste", function (e) {
var output,
$this = $(this),
input = $this.val();
if(e.keyCode != 8) {
input = input.replace(/[^0-9]/g, '');
var area = input.substr(0, 3);
var pre = input.substr(3, 3);
var tel = input.substr(6, 4);
if (area.length < 3) {
output = "(" + area;
} else if (area.length == 3 && pre.length < 3) {
output = "(" + area + ")" + " " + pre;
} else if (area.length == 3 && pre.length == 3) {
output = "(" + area + ")" + " " + pre + "-" + tel;
}
$this.val(output);
}
});
});
<input type="tel" placeholder="(XXX) XXX-XXXX" />
When you're getting the pre code from the number, you're trying to get the index of 4, instead of four digits. So change that, and it should start working:
var pre = input.substr(3, 3);
If you don't want the dynamic filling, the other posted answers might be useful.
Regular expressions are your friend.
var ok = phNum.search(/^\(?\d{3}\D*\d{3}\D*\d{4}$/);
if (ok==0) {
var parts = phNum.match(/^\(?(\d{3})\D*(\d{3})\D*(\d{4})$/);
output.value='('+parts[1]+') '+parts[2]+'-'+parts[3];
}
Accepts: 404-555-1234, 4045551234, (404) 555-1234, etc.
Returns: (404) 555-1234
If you started to use regexp, why dont you go whole way through. Below the code that filter input value and convert it to your look.
Beware, this code only for value that contains only digits. You could block any other types via plugins or your own code. (jquery.numeric plugin is a good choice)
jquery
$(document).on('change', '.js-phone-number', function() {
var
$this = $(this),
number = $this.val();
number = number.replace(/(\d{3})(\d{3})(\d{4})/, '($1)-$2-$3');
$this.val(number);
});
You are fetching variable pre as substring of length 4 and then checking it for it is less than or equal to 3. So, basically your last else if block will never be true.
Change var pre = input.substr(3,3);
Your code will work fine.
How can I remove extra white space (i.e. more than one white space character in a row) from text in JavaScript?
E.g
match the start using.
How can I remove all but one of the spaces between "match" and "the"?
Use regex. Example code below:
var string = 'match the start using. Remove the extra space between match and the';
string = string.replace(/\s{2,}/g, ' ');
For better performance, use below regex:
string = string.replace(/ +/g, ' ');
Profiling with firebug resulted in following:
str.replace(/ +/g, ' ') -> 790ms
str.replace(/ +/g, ' ') -> 380ms
str.replace(/ {2,}/g, ' ') -> 470ms
str.replace(/\s\s+/g, ' ') -> 390ms
str.replace(/ +(?= )/g, ' ') -> 3250ms
See string.replace on MDN
You can do something like this:
var string = "Multiple spaces between words";
string = string.replace(/\s+/,' ', g);
Just do,
var str = "match the start using. Remove the extra space between match and the";
str = str.replace( /\s\s+/g, ' ' );
function RemoveExtraSpace(value)
{
return value.replace(/\s+/g,' ');
}
myString = Regex.Replace(myString, #"\s+", " ");
or even:
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"[ ]{2,}", options);
tempo = regex.Replace(tempo, #" ");
Using regular expression.
var string = "match the start using. Remove the extra space between match and the";
string = string.replace(/\s+/g, " ");
Here is jsfiddle for this
Sure, using a regex:
var str = "match the start using. Remove the extra space between match and the";
str = str.replace(/\s/g, ' ')
This can be done also with javascript logic. here is a reusable function I wrote for that task.
LIVE DEMO
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>result:
<span id="spn">
</span>
</div>
<input type="button" value="click me" onClick="ClearWhiteSpace('match the start using. JAVASCRIPT CAN BE VERY FUN')"/>
<script>
function ClearWhiteSpace(text) {
var result = "";
var newrow = false;
for (var i = 0; i < text.length; i++) {
if (text[i] === "\n") {
result += text[i];
// add the new line
newrow = true;
}
else if (newrow == true && text[i] == " ") {
// do nothing
}
else if (text[i - 1] == " " && text[i] == " " && newrow == false) {
// do nothing
}
else {
newrow = false;
if (text[i + 1] === "\n" && text[i] == " ") {
// do nothing it is a space before a new line
}
else {
result += text[i];
}
}
}
alert(result);
document.getElementById("spn").innerHTML = result;
return result;
}
</script>
</body>
</html>
Try this regex
var st = "hello world".replace(/\s/g,'');
or as a function
function removeSpace(str){
return str.replace(/\s/g,'');
}
Here is a working demo
I figured it out, thank you. I need to move the body to the html. Changed some tags in the body section.
}
else
{
window.alert ("You entered an invalid character (" + enterLetter + ") please re-enter");
secondPrompt();
}
}
</script>
<body onload = "firstPrompt();">
<h2>
Word Checker
</h2>
</body>
</html>
You can increment indexOf each time you find a match-
function indexFind(string, charac){
var i= 0, found= [];
while((i= string.indexOf(charac, i))!= -1) found.push(i++);
return found;
}
indexFind('It\'s more like it is today, than it ever was before','o');
/* returned value: (Array)
6,22,48
*/
Using indexOf recursively:
function findMatches(str, char) {
var i = 0,
ret = [];
while ((i = str.indexOf(char, i)) !== -1) {
ret.push(i);
i += char.length; //can use i++ too if char is always 1 character
};
return ret;
}
Usage in your code:
var matches = findMatches(enterWord, enterLetter);
if (!matches.length) { //no matches
document.write ("String '" + enterWord + "' does not contain the letter '" + enterLetter + ".<br />");
} else {
for (var i = 0; i < matches.length; i++) {
document.write ("String '" + enterWord + "' contains the letter '" + enterLetter + "' at position " + matches[i] + ".<br />");
}
}
Live Demo
Full source (with some tweaks from your last question)
Is it possible to wrap the last words in a string with span tags excluding the first word? So it'd be for example:
var string = 'My super text';
Becomes
My <span>super text</span>
I have this:
var text = string.split(" ");
// drop the last word and store it in a variable
var last = text.pop();
// join the text back and if it has more than 1 word add the span tag
// to the last word
if (text.length > 0) {
return text.join(" ") + " <span>" + last + "</span>";
}
else {
return "<span>" + text.join(" ") + last + "</span>";
}
Which wraps the last word with span tags if it has at least two but not sure how to modify it.
You just need to use text.shift() which will return the first word, instead of text.pop() which returns the last word. Then it will be much easier to accomplish this.
var text= string.split(" ");
// get the first word and store it in a variable
var first = text.shift();
// join the text back and if it has more than 1 word add the span tag
// to the last word
if (text.length > 0) {
return first + " <span>" + text.join(" ") + "</span>";
} else {
return "<span>" + first + "</span>";
}
You could do it with a regular expression.
text = text.replace(/\s(.*)$/, ' <span>$1</span>');
However, you should probably turn the following into a recursive function...
$('body').contents().filter(function() {
return this.nodeType == 3;
}).each(function() {
var node = this;
// Normalise node.
node.data = $.trim(node.data);
node.data.replace(/\s+(.*)\s*$/, function(all, match, offset) {
var chunk = node.splitText(offset);
chunk.parentNode.removeChild(chunk);
var span = document.createElement('span');
span.appendChild(document.createTextNode(' ' + match));
node.parentNode.appendChild(span);
});
});
jsFiddle.
This will allow you to modify text nodes and insert the span elements without messing with serialised HTML.
var space = string.indexOf(' ');
if (space !== -1) {
return string.slice(0,space) + " <span>" + string.slice( space ) + "</span>";
} else {
return "<span>" + string + "</span>";
}
You don't have to split the text, just check if there is a space, and insert a span there.
This code inserts a span after the first space, and if there is no space (idx == -1), the span is put at the beginning of the string:
var idx = string.indexOf(' ');
return string.substr(0, idx + 1) + "<span>" + string.substr(idx + 1) + "</span>";