Given the string below:
"Hello this is a :sample string :hello"
I want to substitute :sample and :hello with something else. How can I do this in JavaScript?
This is what I tried:
var sentence = "Hello this is a :sample string :hello";
var words = sentence.split(" ");
for (var i = 0; i < words.length; i++) {
if (words[i].startsWith(":")) {
words[i] = words[i] + ":";
}
}
sentence = words.join(" ");
console.log(sentence)
Use String.replace(). It can accept specific strings or regular expressions.
Related
I'm trying to change subindex of string array but it's not modifing.There is the jsbin link.
function LetterCapitalize(str) {
var arr = str.split(" ");
var nstr = "";
for (var i = 0; i < arr.length; i++) {
var ltr = arr[i][0];
console.log('ltr: ' + ltr.toUpperCase());
arr[i][0] = ltr.toUpperCase();
nstr += arr[i] + " ";
}
str = nstr.trim();
console.log("result: " + str);
return str;
}
LetterCapitalize("hello world");
You could try something like the following:
function LetterCapitalize(str) {
var arr = str.split(" ");
var nstr = "";
for(var i=0; i<arr.length; i++){
arr[i] = arr[i][0].toUpperCase()+arr[i].slice(1);
nstr+= arr[i] + " ";
}
str = nstr.trim();
console.log("result: " + str);
return str;
}
console.log(LetterCapitalize("hello world"));
The line that does the difference is the following:
arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1);
What we are doing here is to capitalize the first letter of the string at arr[i] and then concatenate the capitalized letter with the rest letters.
That's because (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Character_access):
For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable.
I.e. strings are immutable.
You could as well just use string.replace matching the first char in each word, using a callback function to upper case the character.
Something like this.
var str = "hello world";
var newStr = str.replace(/\b(\w)/g, function(chr) {
return chr.toUpperCase()
})
console.log(newStr)
So I have my code like this:
for (var i = 0; i < str.length; i++) {
str = str.replace("|", "Math.abs(");
str = str.replace("|", ")");
}
Is there anyway to get the same effect using a regex?
Or at least a regex with a function?:
str = str.replace(/?/g, function() {?});
You can use this single regex replace method:
str = str.replace(/\|([^|]+)\|/g, 'Math.abs($1)');
RegEx Demo
You can match the string between |s and then replace them with whatever string you want
str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");
For example,
var str = ["|1|", "|-2|+|22 * -3|"];
for (var i = 0; i < str.length; i++) {
str[i] = str[i].replace(/\|(.*?)\|/g, "Math.abs($1)");
}
console.log(str);
# [ 'Math.abs(1)', 'Math.abs(-2)+Math.abs(22 * -3)' ]
I am learning JavaScript and I am disappointed that the below code doesn't work. It is still a lowercase "i". I was trying to capitalize every letter in the string (hence the for loop) but I wanted to stop and address what was going wrong.
str = 'i ran there';
for(var i = 0; i<str.length; i++){
if(i===0){
str[i] = str[i].charAt(0).toUpperCase();
}
}
console.log(str);
Can someone please describe what is going wrong here?
whats going wrong here is strings in javascript are immutable.
You can't change them. What you can do is create a new string with the change.
If I understand your question, you could do it with something like -
var str = 'i ran there';
var arr = str.split(" ");
var div = document.getElementById("out");
for(var i = 0; i < arr.length; i++){
// The First letter
// arr[i] = arr[i].substring(0,1).toUpperCase() + arr[i].substring(1);
// Every letter
arr[i] = arr[i].toUpperCase();
div.innerHTML += arr[i] + "<br />";
}
<div id="out"></div>
As for what is going on in your code, you can't modify the array backing the String (assuming it is an array) like that.
You are asking for index i of a String str. Because str is a String, you cannot use index values to grab certain characters in the string - try console.log(str[0]) - it will return undefined.
To accomplish what you are trying to do, you would need to simply add to a new string after capitalizing each letter. Example:
str = 'i ran there';
capStr = ''
for(var i = 0; i < str.length; i++){
if(i === 0) capStr += str.charAt(i).toUpperCase();
else capStr += str.charAt(i);
}
console.log(capStr);
You have to create a new string because strings in javascript are immutable:
First get every word separated:
var arrayOfstrings = s.split(" ");
Then you can treat each string like there own word
Fancy way :
var capFirstLetter = arrayOfStrings[index].replace(/^./, function (match) {
return match.toUpperCase();
});
Which is just a regex. The /^./ means the first character in the string. And the rest is self explanatory.
Or this way:
var s = arrayOfStrings[index];
var s2 = s[0].toUpperCase()+ s.substr(0,1);
Or even this really lame way
var s = arrayOfStrings[index];
var newS = "";
for(var i = 0; i < s.length; i++){
if(i == 0) newS+= s[0].toUpperCase();
else newS+= s[i];
}
Of course all these can be done in a forloop to cap them all and put back together:
var s = "hello woorld hello world";
var arrayOfStrings = s.split(" ");
for(var i = 0; i < arrayOfStrings.length; i++){
arrayOfStrings[i]= arrayOfStrings[i].replace(/^./, function(match) {return match.toUpperCase();});
}
var s2 = arrayOfStrings.join(" ");
I'm wondering whether anyone has any insight on converting an array of character codes to Unicode characters, and searching them with a regex.
If you have
var a = [0,1,2,3]
you can use a loop to convert them into a string of the first four control characters in unicode.
However, if you then want to create a regex
"(X)+"
where X == the character code 3 converted to its Unicode equivalent, the searches never seem to work. If I check for the length of the string, it's correct, and .* returns all the characters in the string. But I'm having difficulties constructing a regex to search the string, when all I have to begin with is the character codes. Any advise?
Edit:
var a = [0,1,2,3,0x111];
str = "";
for(var i = 0; i < a.length; i++) {
str += String.fromCharCode(a[i]);
}
var r = [0x111]
var reg = ""
reg += "(";
for(var i = 0; i < r.length; i++) {
var hex = r[i].toString(16);
reg += "\\x" + hex;
}
reg += ")";
var res = str.match(RegExp(reg))[0];
Edit
//Working code:
var a = [0,1,2,3,0x111];
str = "";
for(var i = 0; i < a.length; i++) {
str += String.fromCharCode(a[i]);
}
var r = [3,0x111]
var reg = ""
reg += "(";
for(var i = 0; i < r.length; i++) {
var hex = r[i].toString(16);
reg += ((hex.length > 2) ? "\\u" : "\\x") + ("0000" + hex).slice((hex.length > 2) ? -4 : -2);
}
reg += ")";
var res = str.match(RegExp(reg))[0];
With changes to a few details, the example can be made to work.
Assuming that you are interested in printable Unicode characters in general, and not specifically the first four control characters, the test vector a for the string "hello" would be:
var a = [104, 101, 108, 108, 111]; // hello
If you want to match both 'l' characters:
var r = [108, 108]
When you construct your regular expression, the character code must be in hexadecimal:
reg += "\\x" + ("0" + r[i].toString(16)).slice(-2);
After that, you should see the results you expect.
i am trying to create a program that stores words in an Array, what I've done is whatever the program finds a separator (" " or ",") it pushes it in the array, my problem here is that it store even the separators with it (i must use the array SEPARATORS).
var sentence = prompt("");
var tab = [];
var word = "" ;
var separators = [" ", ","];
for(var i = 0 ; i< sentence.length ; i++){
for(var j = 0 ; j < separators.length ; j++){
if(sentence.charAt(i) != separators[j] && j == separators.length-1){
word += sentence.charAt(i);
}else if(sentence.charAt(i) == separators[j]){
tab.push(word);
word = "";
}
}
}
tab.push(word);
console.log(tab);
You can try this:
var text = 'Some test sentence, and a long sentence';
var words = text.split(/,|\s/);
If you don't want empty strings:
var words = text.split(/,|\s/).filter(function (e) {
return e.length;
});
console.log(words); //["some", "test", "sentence", "and", "a", "long", "sentence"]
If you need to use the array you can try this:
var text = 'Some test sentence, and a long sentence',
s = [',', ' '],
r = RegExp('[' + s.join('') + ']+'),
words = text.split(r);
I would just use regex:
var words = sentence.split(/[, ]+/);
If you want to fix your code, use indexOf instead of a for loop:
for (var i = 0; i < sentence.length; i++) {
if (separators.indexOf(sentence.charAt(i)) === -1) {
word += sentence.charAt(i);
} else {
tab.push(word);
word = "";
}
}
After reexamining the problem, I think you need a combination of native string functions and the compact method from the excellent underscore library which removes 'falsy' entries in an array:
$('#textfield).keyup(analyzeString);
var words;
function analyzeString(event){
words = [];
var string = $('#textfield).val()
//replace commas with spaces
string = string.split(',').join(' ');
//split the string on spaces
words = string.split(' ');
//remove the empty blocks using underscore compact
_.compact(words);
}