I want to convert a XRegExp function to pure JavaScript RegExp. Basically all non-alphanumeric character will be replaced with "_" including spaces.
The text
This is a sample text *\&^%$##!~'
will be like
This_is_a_sample_text____________
I have the following code.
var text = "This is a sample text *\&^%$##!~'";
var matchAlphaNumeric = new XRegExp('[\\p{L}\\p{N}]');
var result = substituteNotAcceptedCharactersforTag(text, matchAlphaNumeric);
function substituteNotAcceptedCharactersforTag(text, regex) {
var tagWithAlphaAndNumeric = '';
for (var i = 0; i < text.length; i++) {
var characterBeingTested = text.charAt(i);
if (XRegExp.test(characterBeingTested, regex) === true) {
tagWithAlphaAndNumeric += characterBeingTested.toLowerCase();
} else {
tagWithAlphaAndNumeric += '_';
}
}
return tagWithAlphaAndNumeric;
}
Replace all non-alphanumeric characters with _:
s = s.replace(/[^0-9A-Za-z]/g, '_');
Related
content = '5<x<div></div>'
Basically I am looking for a regular expression that will make the string like above into 5<x<div></div>
5x<div></div> will still be 5x<div></div>. I am just trying to escape unclosed html tags
If there is such a library then I will be very happy to use it as long as it meets my main goal of trying to escape unclosed html tags
Rewrite each open tag character "<" with the symbol + unique value ... in this case ",,#*&,,"
Split the string at the unique value
The "replaceString ()" function checks if the passed value is really a tag ... whether both "<" and ">" characters are present in the string. If not present, rewrite the character with "& lt;".
The whole process is repeated for the symbol ">"
This is not the most beautiful solution to this task but it works.
var str = '5<x<div>s>7</div>';
for (var i = 0; i < 2; i++) {
if (i === 0) {
var str2 = str.replace(/</gi, ",,#*&,,<");
var spl = str2.split(",,#*&,,");
} else {
var str2 = str.replace(/>/gi, ">,,#*&,,");
var spl = str2.split(",,#*&,,");
}
replaceString(spl);
}
function replaceString(spl) {
for (let i = 0; i < spl.length; i++) {
if (spl[i].indexOf('<') > -1 && spl[i].indexOf('>') > -1) {
//.......
} else {
if (spl[i].indexOf('<') > -1) {
spl[i] = spl[i].replace(/</gi, "<");
}
else if (spl[i].indexOf('>') > -1) {
spl[i] = spl[i].replace(/>/gi, ">");
}
}
}
str = spl.join('');
}
console.log(str);
I'm working on alternating the case of a string (for example asdfghjkl to AsDfGhJkL).
I tried to do this. I found some code that is supposed to do it, but it doesn't seem to be working.
var str="";
var txt=document.getElementById('input').value;
for (var i=0; i<txt.length; i+2){
str = str.concat(String.fromCharCode(txt.charCodeAt(i).toUpperCase()));
}
Here's a quick function to do it. It makes the entire string lowercase and then iterates through the string with a step of 2 to make every other character uppercase.
var alternateCase = function (s) {
var chars = s.toLowerCase().split("");
for (var i = 0; i < chars.length; i += 2) {
chars[i] = chars[i].toUpperCase();
}
return chars.join("");
};
var txt = "hello world";
console.log(alternateCase(txt));
HeLlO WoRlD
The reason it converts the string to an array is to make the individual characters easier to manipulate (i.e. no need for String.prototype.concat()).
Here an ES6 approach:
function swapCase(text) {
return text.split('').map((c,i) =>
i % 2 == 0 ? c.toLowerCase() : c.toUpperCase()
).join('');
}
console.log(swapCase("test"))
You should iterate the string and alternate between upper-casing the character and lower-casing it:
for (var i=0; i<txt.length; i++) {
var ch = String.fromCharCode(txt.charCodeAt(i);
if (i % 2 == 1) {
ch = ch.toUpperCase();
} else {
ch = ch.toLowerCase();
}
str = str.concat(ch);
}
So the goal of this task is translate english input values into french and vice versa. The problem here is that I don't know how to split the whole input by spaces to get all the words one by one and translate them one by one. Thank you :)
function translateInput(){
for(i = 0; i < ('input').length; i++){
('input').eq(i).val(('value').eq(i).text());
}
}
var translateText = function() {
var translationType = document.getElementById('translation').value;
if (translationType === 'englishToFrench') {
console.log('translation used: English to French');
return 'code1';
}else if(translationType === 'frenchToEnglish'){
console.log('translation used: French to English');
return 'code2';
}else{
return "No valid translation selected.";
}
};
You can use the split function to split the string at its spaces into an array.
var str = YOUR_STRING;
var array = str.split(" ");
http://www.w3schools.com/jsref/jsref_split.asp
Then you can loop through the array and translate word by word.
var arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
alert(array[i]);
//Translate string
}
Or you can use a Regular Expression, by the way you can practice in a Regex Playground.
var myString = "Hello, my name is JavaScript";
var tokens = a.match(/\w+'?\w*/g); //Assuming you can take words like {"Bonsanto's", "Asus'"}
tokens.forEach(function(word){
console.log(word);
});
I'm struggling too much for this task. I need to make it; check to see if the word that i had written matches up to the word that is in the array. (single letter). if it does, it should replace the underscores with the characters that are in that word! How should I do it?
this is for a game like hangman btw
This is my code:
<script>
var words = ["kite", "boom", "zoom", "tall", "table", "biscuit", "pie"];
window.addEventListener("load", function() {
var submitbtn = document.getElementById("button")
var userInput = document.getElementById("userInput");
submitbtn.addEventListener("click", checkAnswer, false);
var wordElt = document.getElementById("word");
var word = words[Math.floor(Math.random() * words.length)];
for ( var i=0; i < word.length; i++ ) {
//display += "_ ";
wordElt.textContent += " _ ";
}
var split = word.split("");
console.log(word)
});
function check(){
}
You can't replace a letter in string, because javascript strings are immutable - see this answer from which you can borrow
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
Then (if you code the Hangman game) you can replace the occurences using string indexOf method:
var theWord = "H___o";
var theLetter = "l";
var keyWord = "Hello";
while(true) {
var i = keyWord.indexOf(theLetter);
if(i==-1) break;
theWord = theWord.replaceAt(i,theLetter);
keyWord = keyWord.replaceAt(i,"_");
}
// theWord = H_llo
// keyWord = He__o
I am trying to replace all dots for comma and commas for dots and was wondering what is the best practice for doing this. If I do it sequentially, then the steps will overwrite each other.
For example:
1,234.56 (after replacing commas) --> 1.234.56 (after replacing dots) --> 1,234,56
Which is obviously not what I want.
One option I guess is splitting on the characters and joining afterwards using the opposite character. Is there an easier/better way to do this?
You could use a callback
"1,234.56".replace(/[.,]/g, function(x) {
return x == ',' ? '.' : ',';
});
FIDDLE
If you're going to replace more than two characters, you could create a convenience function using a map to do the replacements
function swap(str, swaps) {
var reg = new RegExp('['+Object.keys(swaps).join('')+']','g');
return str.replace(reg, function(x) { return swaps[x] });
}
var map = {
'.':',',
',':'.'
}
var result = swap("1,234.56", map); // 1.234,56
FIDDLE
You could do the following:
var str = '1,234.56';
var map = {',':'.','.':','};
str = str.replace(/[,.]/g, function(k) {
return map[k];
});
Working Demo
Do it in stages using placeholder text:
var foo = '1,234.56';
foo = foo
.replace(',', '~comma~')
.replace('.', '~dot~')
.replace('~comma~', '.')
.replace('~dot~', ',')
You could use a for loop. Something like:
var txt = document.getElementById("txt");
var newStr = "";
for (var i = 0; i < txt.innerHTML.length; i++){
var char = txt.innerHTML.charAt(i);
if (char == "."){
char = ",";
}else if (char == ","){
char = ".";
}
newStr += char;
}
txt.innerHTML = newStr;
Here's a fiddle:
http://jsfiddle.net/AyLQt/1/
Have to say though, #adenoeo's answer is way more slick :D
In javascript you can use
var value = '1.000.000,55';
var splitValue = value.split('.');
for (var i = 0; i < splitValue.length; i++) {
var valPart = splitValue[i];
var newValPart = valPart.replace(',', '.');
splitValue[i] = newValPart;
}
var newValue = splitValue.join(',');
console.log(newValue);