my replace is not working in my function? [duplicate] - javascript

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
var jtj_code_lines = []; // this array will hold all the jtj codes line
var JTJ = function(j){
j = j.replace(" ","");
jtj_code_lines = j.split(';'); // splitting all the lines seperated from ;
for(var i=0; i<jtj_code_lines.length; i++){
if(jtj_code_lines[i].charAt(0) === '*'){ // * means that the following word is the name of a method that will perform some action
var q1 = jtj_code_lines[i].replace('*', ''),
q1_pos_1 = q1.indexOf('['); // find the position of the keyword [
var q1_funcname = q1.slice(0, q1_pos_1); // it find the name of that perticular function
if(q1_funcname === "Message"){ // this checks weather the function name is message
var q1_pos_2 = q1.indexOf(']'), // this ifnds the position of keyword ]
q1_func_value = q1.slice(q1_pos_1+1, q1_pos_2); // this finds what is written inside [] and accepts as the value of Message
alert(q1_func_value);
}else{
}
}
}
};
so the above function is pretty simple it finds the specific text written in the braces, i mean that if you write :
JTJ('*Message[hi];')
then it will alert hi and this is quit simple and this is alerting as expected but the problem is coming that if any * is after white space then that perticular thing is not being alerted, so the following have the same condition,*Message[go ]; starts with whitespace so it is not being alerted :
JTJ('*Message[sanmveg];*Message[saini]; *Message[go ];')
but i have a this line j = j.replace(" ",""); to remove all the white spaces, then why it is not working? is there any other way to do this?
thanks.

Fix: j = j.replace(/\s/gi,"");
this would remove all " " with "", in short it would act as replaceAll.
Before it was just replacing first matched " " with "".

Related

.Trim Is Not A Function Error When Trying To Remove The Space From Returned Data [duplicate]

This question already has answers here:
Javascript - Apply trim function to each string in an array
(12 answers)
Closed 3 years ago.
I have a DataTable which is being populated by JSON. The days of the week (for example) are returning as a string which i am applying .split(',') to and is working in my forEach function, but i need to apply a class to my days returned buttons but due to the space in the string it only falls into my 'Mon' button and not the rest due to the space.
Working code
var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',');
console.log(splitSelectedDays);
splitSelectedDays.forEach(day => {
if(day == 'Mon') {
alert('in Mon')
$('#mon').removeClass('btn-default');
$('#mon').addClass('btn-primary');
}
if (day == 'Tue') {
alert('in Tue')
$('#tue').removeClass('btn-default');
$('#tue').addClass('btn-primary');
}
// AND SO ON
})
This also returns
I have tried the following but none are working
var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',').trim();
and
var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',').trim();
var test = splitSelectedDays.trim();
also thruught about trying in the actual loop as each one returned as a string using the below
splitSelectedDays.forEach(day => {
splitSelectedDays.trim();
But always get the function error.
I am wanting to remove the space, then lowercase the value then i can use the var in on addClass function rather than an IF for each day of the week
split in selectedDays.split(',').trim(); will create an array. There is no trim for array. So you can iterate the array and apply trim if it is a string
You can do like this
splitSelectedDays.forEach(day => {
let val = day.trim();
// rest of the code
})
var splitSelectedDays = selectedDays.split(',').trim();
This is your problematic line.
selectedDays.split(',') will return an array of strings. Trim is a method on a string, not an array of strings, that removes leading/trailing whitespace.
You will have to apply trim() to each individual element in the array.
For example
var splitSelectedDays = selectedDays.split(',');
for (var i=0; i < splitSelectedDays.length; i++)
{
splitSelectedDays[i] = splitSelectedDays[i].trim();
}

Why is array[0] = array[0].toUpperCase() working, while array[0][0] = array[0][0].toUpperCase() isn't [duplicate]

This question already has answers here:
string.charAt(x) or string[x]?
(7 answers)
Capitalize words in string [duplicate]
(21 answers)
Closed 4 years ago.
TO BE CLEAR:
I don't want to know how to capitalize, but rather I want to know why i can change it in one-dimensional, but not 2-dimensional
I'm doing some coding challenges to get familiar with JavaScript.
I capitalized the first Letter of each word in a given string.
I split the string into a word-seperated array via String.match(regex);
var word_array = str.match(/\w(\w)*/g);
And I then made from the word another letter-seperated array to change single letters. (also with regex)
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
And this works just fine.
But I wanted it a bit shorter, so I tried to do the action on the letter on the second dimension of the word_array, but with no effect at all.
word_array[i][0] = word_array[i][0].toUpperCase();
Full-Code-Snippet
const input = document.querySelector("#string"),
button = document.querySelector("#DOIT");
button.addEventListener("click", function(){
LetterCapitalize(input.value);
});
function LetterCapitalize(str) {
var word_array = str.match(/\w(\w)*/g);
for(let i = 0; i < word_array.length; i++){
//This part works
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
word_array[i] = letter_array.join("");
//this doesn't
/*
word_array[i][0] = word_array[i][0].toUpperCase();
console.log(word_array[i][0]);
*/
}
console.log(word_array);
str = word_array.join(" ");
return str;
}
<input id="string" type="text"/>
<button id="DOIT">DO IT</button>
This wouldnt work wouldn't work since Strings are immutable in javascript. the
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
code snipped worked as you converted your strings to a list/array which is mutable by nature. although, id like to point out that this question might be a duplicate. here is a capitalization in javascript question

Unable to Get Output From While Loop in Javascript

I'm working on my final project of the Winter 2017 quarter to demonstrate how to use Regular Expressions in both C# and JavaScript code behind pages. I've got the C# version of my demonstration program done, but the JavaScript version is making me pull what little hair I have left on my head out (no small achievement since I got a fresh buzz cut this morning!). The problem involves not getting any output after applying a Regular Expression in a While loop to get each instance of the expression and printing it out.
On my HTML page I have an input textarea, seven radio buttons, an output textarea, and two buttons underneath (one button is to move the output text to the input area to perform multiple iterations of applying expressions, and the other button to clear all textareas for starting from scratch). Each radio button links to a function that applies a regular expression to the text in the input area. Five of my seven functions work; the sixth is the one I can't figure out, and the seventh is essentially the same but with a slightly different RegEx pattern, so if I fix the sixth function, the seventh function will be a snap.
(I tried to insert/upload a JPG of the front end, but the photo upload doesn't seem to be working. Hopefully you get the drift of what I've set up.)
Here are my problem children from my JS code behind:
// RegEx_Demo_JS.js - code behind for RegEx_Demo_JS
var inputString; // Global variable for the input from the input text box.
var pattern; // Global variable for the regular expression.
var result; // Global variable for the result of applying the regular expression to the user input.
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder()
{
var strings = [];
this.append = function (string)
{
string = verify(string);
if (string.length > 0) strings[strings.length] = string;
}
this.appendLine = function (string)
{
string = verify(string);
if (this.isEmpty())
{
if (string.length > 0) strings[strings.length] = string;
else return;
}
else strings[strings.length] = string.length > 0 ? "\r\n" + string : "\r\n";
}
this.clear = function () { strings = []; };
this.isEmpty = function () { return strings.length == 0; };
this.toString = function () { return strings.join(""); };
var verify = function (string)
{
if (!defined(string)) return "";
if (getType(string) != getType(new String())) return String(string);
return string;
}
var defined = function (el)
{
// Changed per Ryan O'Hara's comment:
return el != null && typeof(el) != "undefined";
}
var getType = function (instance)
{
if (!defined(instance.constructor)) throw Error("Unexpected object type");
var type = String(instance.constructor).match(/function\s+(\w+)/);
return defined(type) ? type[1] : "undefined";
}
}
Within the code of the second radio button (which will be the seventh and last function to complete), I tested the ScriptBuilder with data in a local variable, and it ran successfully and produced output into the output textarea. But I get no output from this next function that invokes a While loop:
function RegEx_Match_TheOnly_AllInstances()
{
inputString = document.getElementById("txtUserInput").value;
pattern = /(\s+the\s+)/ig; // Using an Flag (/i) to select either lowercase or uppercase version. Finds first occurrence either as a standalone word or inside a word.
//result = pattern.exec(inputString); // Finds the first index location
var arrResult; // Array for the results of the search.
var sb = getStringBuilder(); // Variable to hold iterations of the result and the text
while ((arrResult = pattern.exec(inputString)) !==null)
{
sb.appendLine = "Match: " + arrResult[0] ;
}
document.getElementById("txtRegExOutput").value = sb.toString();
/* Original code from C# version:
// string pattern = #"\s+(?i)the\s+"; // Same as above, but using Option construct for case insensitive search.
string pattern = #"(^|\s+)(?i)the(\W|\s+)";
MatchCollection matches = Regex.Matches(userTextInput, pattern);
StringBuilder outputString = new StringBuilder();
foreach (Match match in matches)
{
string outputRegExs = "Match: " + "\"" + match.Value + "\"" + " at index [" + match.Index + ","
+ (match.Index + match.Length) + "]" + "\n";
outputString.Append(outputRegExs);
}
txtRegExOutput.Text = outputString.ToString();
*/
} // End RegEx_Match_The_AllInstances
I left the commented code in to show what I had used in the C# code behind version to illustrate what I'm trying to accomplish.
The test input/string I used for this function is:
Don’t go there. If you want to be the Man, you have to beat The Man.
That should return two hits. Ideally, I want it to show the word that it found and the index where it found the word, but at this point I'd be happy to just get some output showing every instance it found, and then build on that with the index and possibly the lastIndex.
So, is my problem in my While loop, the way I'm applying the StringBuilder, or a combination of the two? I know the StringBuilder code works, at least when not being used in a loop and using some test data from the site I found that code. And the code for simply finding the first instance of "the" as a standalone or inside another word does work and returns output, but that doesn't use a loop.
I've looked through Stack Overflow and several other JavaScript websites for inspiration, but nothing I've tried so far has worked. I appreciate any help anyone can provide! (If you need me to post any other code, please advise and I'll be happy to oblige.)

Javascript array length through user input

I have a problem in Javascript I want to make a form which have one input text field and one button when I click on the button window.prompt is called.
It will prompt depend upon my array length but I want array length get through input text field when I write 10 it will prompt 10 times when I write 2 it will prompt 2 times.
How can i write this type of query?
I tried this code but its not working.
words = new Array (4);
function a() {
for ( k = 0 ; k < words.length ; k = k + 1 ) {
words[ k ] = window.prompt( "Enter word # " + k, "" ) ;
}
}
Maybe you forgot to call your function a().
Some remarks about your code:
You don't have to specify an initial array size, e.g. words = [] or words = new Array() is enough.
Also k=k+1 is usually written as k++.
A remark about asking questions:
Use punctuation to make sentences! Your whole question is one sentence.
Hopefully it's just the snippet of code but I hope you are using var somewhere to declare all those variables.
Otherwise this should do the trick, however not sure what you are trying to achieve but this sounds like a bad user experience.
Here is the jsffidle http://jsfiddle.net/R2bCz/1/
function Handler(event) {
var count = event.target.value;
var i = 0;
var words = [];
var word;
for (; i < count; i++) {
word = window.prompt("Enter word # " + i, "");
words.push(word);
}
}
$("#multi").on("change", Handler);

How to detect image file extension in a string with JavaScript [duplicate]

This question already has answers here:
How can I get file extensions with JavaScript?
(36 answers)
Closed 9 years ago.
I would like to know how can I detect an image in a string with JavaScript. For example, I have an input type text that has the following value, "Hey check this out https://exmaple.com/image.jpg" I want to wrap 'https://exmaple.com/image.jpg' in an tag so it can show the image right away in my site. Thank you, I tried using the split function in JavaScript but I don't know how to detect the image extension in the string.
Use lastIndexOf()
var str = "https://example.com/image.jpg";
var dotIndex = str.lastIndexOf('.');
var ext = str.substring(dotIndex);
Fiddle
You'd probably want to use a regular expression like the following in order to find any image type, and make sure you're not returning other junk that you don't want. E.g.
'https://exmaple.com/image.jpg'.match(/[^/]+(jpg|png|gif)$/)
-> ["image.jpg", "jpg"]
var str = "https://example.com/image.jpg";
var extArray = str.split(".");
var ext = extArray[extArray.length - 1];
Try this.
function searchText(text)
{
var arr = text.match("/(http|ftp|https)://[\w-]+(\.[\w-]+)+([\w.,#?^=%&:/~+#-]*[\w#?^=%&/~+#-])?/");
for (var i=0; i<arr.length; i++)
{
//Make tags where 'arr[i]' is your url.
}
}
HINT: (Please use logic based on your needs)
you have to split string somehow based on your condition and check if the string has . or something
var a = "Hey check this out https://exmaple.com/image.jpg";
var text = a.split(' ');
if text array has your condition then assign to variable filename
if(jQuery.inArray(".", text)!==-1) { //i dont prefer only .
filename = text[jQuery.inArray(".", text)];
}
separate the extension
function getExt(filename)
{
var ext = filename.split('.').pop();
if(ext == filename) return "";
return ext;
}

Categories