Javascript toArray to avoid cutting characters - javascript

I have a quick question.
This is my code, and problem with it is when i run some emojis thro this it displays them as ?, cause it cuts the emoji in half.
angular.module('Joe.filters').filter("initials", function() {
return function(string) {
if (string) {
var words = string.split(" ");
if (words.length) {
string = words[0].charAt(0);
if (words[1]) {
string += words[1].charAt(0);
}
}
}
return string;
};
});
Now, im thinking if i can solve this with toArray, and if yes, how?
Note: if i run in console the "fix" with array.
j = '📌';
"📌"
j.length
2
s = _.toArray(j)
["📌"]
s.length
1
Thanks in advance!!

In ES6, .charAt and [indexing] still work with 16-bit units, but String.iterator is aware of 32-bit chars. So, to extract the first char which is possibly beyond the plane 0, you have to force iteration on the string, for example:
word = '📌HELLO';
let b = [...word][0]
// or
let [c] = word
console.log(b, c)
Another option is to extract the first code point and convert it back to a character:
let a = String.fromCodePoint(word.codePointAt(0))
To answer the bonus question, I have this rather trivial function in my "standard repertoire"
let first = ([a]) => a
Using this func, your initials logic can be written as
let initials = str => str.split(' ').slice(0, 2).map(first).join('')

Related

Writing a Hexadecimal Escape Character Sequence using Variables

Testing Hex Character Codes
Problem
What does a Vertical Tab or a Backspace character actually do? I want to find out.
My experiment is to find out exactly what happens when every hex character is put into a string. I thought the best way to do this would be to created a nested loop to go through each of the 16 hexadecimal characters to create each possible 2 digit hex character code.
I soon discovered that you cannot use the \x escape character with interpolated variables, and so I expect what I have set out to do might be impossible.
const hexCharacters = "0123456789ABCDEF";
let code = "";
let char1 = "";
let char2 = "";
for (charPos1 = 0; charPos1 < hexCharacters.length; charPos1++) {
for (charPos2 = 0; charPos2 < hexCharacters.length; charPos2++) {
char1 = hexCharacters[charPos1];
char2 = hexCharacters[charPos2];
code = `${char1}${char2}`;
printHexChar(code);
}
}
function printHexChar(string) {
let output = `<p>Hex Code ${string} = \x${string}</p>`; // THE PROBLEM IS CLEAR
document.write(output)
}
I know it will also probably fail once it gets past 7F or whichever is the last character in the set, but that's not the main issue here! :D
Potential solution
string.prototype.fromCharCode
This sort of string method approach would seem to be the answer, but it is meant for U-16 character codes, and that is not what I wanted to test. There doesn't seem to be an existing string method for hex codes. Probably because nobody would ever want one, but nevertheless it would be cool.
Conclusion
Is there any way to create an escape character sequence from assembled parts that will render not as plain text, but as a proper escape character sequence?
Apologies if this has been asked before in some form, but with my feeble understanding of things I just couldn't find an answer.
You can use String.fromCharCode with parseInt.
`<p>Hex Code ${string} = ${String.fromCharCode(parseInt(string, 16))}</p>`;
const hexCharacters = "0123456789ABCDEF";
let code = "";
let char1 = "";
let char2 = "";
for (charPos1 = 0; charPos1 < hexCharacters.length; charPos1++) {
for (charPos2 = 0; charPos2 < hexCharacters.length; charPos2++) {
char1 = hexCharacters[charPos1];
char2 = hexCharacters[charPos2];
code = `${char1}${char2}`;
printHexChar(code);
}
}
function printHexChar(string) {
let output = `<p>Hex Code ${string} = ${String.fromCharCode(parseInt(string, 16))}</p>`;
document.write(output)
}
eval works as well, though it should generally be avoided.
`<p>Hex Code ${string} = ${eval('"\\x'+string+'"')}</p>`
If you want to output \x literally, then in a string literal you need to escape the escape character, so `\\x`.
string.prototype.fromCharCode [...] is meant for U-16 character codes
JavaScript uses one character encoding. The following strings are all equal:
let a = String.fromCharCode(27);
let b = "\x1B";
let c = "\u001B";
console.log(a === b, b === c);
If I understand correctly, you want to produce a string literal that shows \x escape sequences -- not the actual character:
// Prepare string
let chars = Array.from({length: 128}, (_, i) => String.fromCharCode(i))
.join("");
// Escape them
let escaped = Array.from(chars, ch => `\\x${ch.charCodeAt().toString(16).padStart(2, "0")}`).join("");
console.log(escaped);
But you might also use JSON.stringify. Although it uses different escape sequences (\u instead of \x), and only for non-display characters, it will be the exact same string when evaluated. Here is a demo:
// Prepare string
let chars = Array.from({length: 128}, (_, i) => String.fromCharCode(i))
.join("");
// Escape them
let escaped = '"' + Array.from(chars, ch => `\\x${ch.charCodeAt().toString(16).padStart(2, "0")}`).join("") + '"';
console.log(escaped);
// Or JSONify them
let json = JSON.stringify(chars);
console.log(json);
// Compare them, when evaluated:
console.log(eval(escaped) === eval(json));
Finally, note that there is nothing special about hexadecimal: it is just a representation of an integer. In the end, it is the numerical value that is important, not the representation of it. It is that numerical value that corresponds to a character.
Addendum
If you prefer code that sticks to old-style JavaScript, here is something equivalent of the last code snippet:
// Prepare string
let chars = "";
for (let i = 0; i < 128; i++) {
chars += String.fromCharCode(i);
}
// Escape the characters in this string
let escaped = '"';
for (let i = 0; i < chars.length; i++) {
let ch = chars.charCodeAt(i);
let hex = ch.toString(16);
if (hex.length === 1) hex = "0" + hex;
escaped += "\\x" + hex;
}
escaped += '"';
console.log(escaped);
// Or JSONify them
let json = JSON.stringify(chars);
console.log(json);
// Compare them, when evaluated:
console.log(eval(escaped) === eval(json));

Problem with finding proper regular expression in my solution from Codewars task named Mumbling

I am looking at the Mumbling code challenge on CodeWars:
The examples below show you how to write function accum:
Examples:
accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"
The parameter of accum is a string which includes only letters from a..z and A..Z.
This is my attempt:
function accum(s) {
const holdArr = [...s];
const tempArr = [];
for (let i = 0; i < holdArr.length; i++) {
tempArr.push(holdArr[i].repeat(i + 1).toLowerCase());
}
return tempArr.join("-").replace(/(^|-\w)/g, (x) => x.toUpperCase());
}
The problem is that within input like:
console.log(accum("abCd"));
...it gives output: a-Bb-Ccc-Ddd, but it should give A-Bb-Ccc-Dddd. How can I tune the RegEx to get it?
If you use /(^|-\w)/g, then the letter will be matched only if it follows an hypen.
You should instead use /(^|-)\w/g for matching the letter also when it follows the beginning of the string.
Not a direct answer to the question, but a way to do it without regex:
const accum = (s, c = 0) =>
[...s.toLowerCase()].map((l) => `${l.toUpperCase()}${l.repeat(c++)}`).join('-');
console.log(accum('abcd')); // A-Bb-Ccc-Dddd
As an aside if you want to find the first word character in a pattern, you can put a word-boundary before it: \b\w.
It matches after a - or a the start of the string.

JS Regex returning -1 & 0

I was tasked with the following:
take a string
print each of the vowels on a new line (in order) then...
print each of the consonants on a new line (in order)
The problem I found was with the regex. I originally used...
/[aeiouAEIOU\s]/g
But this would return 0 with a vowel and -1 with a consonant (so everything happened in reverse).
I really struggled to understand why and couldn't for the life of me find the answer. In the end it was simple enough to just invert the string but I want to know why this is happening the way it is. Can anyone help?
let i;
let vowels = /[^aeiouAEIOU\s]/g;
let array = [];
function vowelsAndConsonants(s) {
for(i=0;i<s.length;i++){
//if char is vowel then push to array
if(s[i].search(vowels)){
array.push(s[i]);
}
}
for(i=0;i<s.length;i++){
//if char is cons then push to array
if(!s[i].search(vowels)){
array.push(s[i]);
}
}
for(i=0;i<s.length;i++){
console.log(array[i]);
}
}
vowelsAndConsonants("javascript");
if(vowels.test(s[i])){ which will return true or false if it matches, or
if(s[i].search(vowels) !== -1){ and if(s[i].search(vowels) === -1){
is what you want if you want to fix your code.
-1 is not falsey so your if statement will not function correctly. -1 is what search returns if it doesn't find a match. It has to do this because search() returns the index position of the match, and the index could be anywhere from 0 to Infinity, so only negative numbers are available to indicate non-existent index:
MDN search() reference
Below is a RegEx that matches vowel OR any letter OR other, effectively separating out vowel, consonant, everything else into 3 capture groups. This makes it so you don't need to test character by character and separate them out manually.
Then iterates and pushes them into their respective arrays with a for-of loop.
const consonants = [], vowels = [], other = [];
const str = ";bat cat set rat. let ut cut mut,";
for(const [,cons,vow,etc] of str.matchAll(/([aeiouAEIOU])|([a-zA-Z])|(.)/g))
cons&&consonants.push(cons) || vow&&vowels.push(vow) || typeof etc === 'string'&&other.push(etc)
console.log(
consonants.join('') + '\n' + vowels.join('') + '\n' + other.join('')
)
There are a couple of inbuilt functions available:
let some_string = 'Mary had a little lamb';
let vowels = [...some_string.match(/[aeiouAEIOU\s]/g)];
let consonents = [...some_string.match(/[^aeiouAEIOU\s]/g)];
console.log(vowels);
console.log(consonents);
I think that you don't understand correctly how your regular expression works. In the brackets you have only defined a set of characters you want to match /[^aeiouAEIOU\s]/g and further by using the caret [^]as first in your group, you say that you want it to match everything but the characters in the carets. Sadly you don't provide an example of input and expected output, so I am only guessing, but I thing you could do the following:
let s = "avndexleops";
let keep_vowels = s.replace(/[^aeiouAEIOU\s]/g, '');
console.log(keep_vowels);
let keep_consonants = s.replace(/[aeiouAEIOU\s]/g, '');
console.log(keep_consonants);
Please provide example of expected input and output.
You used:
/[^aeiouAEIOU\s]/g
Instead of:
/[aeiouAEIOU\s]/g
^ means "not", so your REGEX /[^aeiouAEIOU\s]/g counts all the consonants.

Get first letter of each word in a string, in JavaScript

How would you go around to collect the first letter of each word in a string, as in to receive an abbreviation?
Input: "Java Script Object Notation"
Output: "JSON"
I think what you're looking for is the acronym of a supplied string.
var str = "Java Script Object Notation";
var matches = str.match(/\b(\w)/g); // ['J','S','O','N']
var acronym = matches.join(''); // JSON
console.log(acronym)
Note: this will fail for hyphenated/apostrophe'd words Help-me I'm Dieing will be HmImD. If that's not what you want, the split on space, grab first letter approach might be what you want.
Here's a quick example of that:
let str = "Java Script Object Notation";
let acronym = str.split(/\s/).reduce((response,word)=> response+=word.slice(0,1),'')
console.log(acronym);
I think you can do this with
'Aa Bb'.match(/\b\w/g).join('')
Explanation: Obtain all /g the alphanumeric characters \w that occur after a non-alphanumeric character (i.e: after a word boundary \b), put them on an array with .match() and join everything in a single string .join('')
Depending on what you want to do you can also consider simply selecting all the uppercase characters:
'JavaScript Object Notation'.match(/[A-Z]/g).join('')
Easiest way without regex
var abbr = "Java Script Object Notation".split(' ').map(function(item){return item[0]}).join('');
This is made very simple with ES6
string.split(' ').map(i => i.charAt(0)) //Inherit case of each letter
string.split(' ').map(i => i.charAt(0)).toUpperCase() //Uppercase each letter
string.split(' ').map(i => i.charAt(0)).toLowerCase() //lowercase each letter
This ONLY works with spaces or whatever is defined in the .split(' ') method
ie, .split(', ') .split('; '), etc.
string.split(' ') .map(i => i.charAt(0)) .toString() .toUpperCase().split(',')
To add to the great examples, you could do it like this in ES6
const x = "Java Script Object Notation".split(' ').map(x => x[0]).join('');
console.log(x); // JSON
and this works too but please ignore it, I went a bit nuts here :-)
const [j,s,o,n] = "Java Script Object Notation".split(' ').map(x => x[0]);
console.log(`${j}${s}${o}${n}`);
#BotNet flaw:
i think i solved it after excruciating 3 days of regular expressions tutorials:
==> I'm a an animal
(used to catch m of I'm) because of the word boundary, it seems to work for me that way.
/(\s|^)([a-z])/gi
Try -
var text = '';
var arr = "Java Script Object Notation".split(' ');
for(i=0;i<arr.length;i++) {
text += arr[i].substr(0,1)
}
alert(text);
Demo - http://jsfiddle.net/r2maQ/
Using map (from functional programming)
'use strict';
function acronym(words)
{
if (!words) { return ''; }
var first_letter = function(x){ if (x) { return x[0]; } else { return ''; }};
return words.split(' ').map(first_letter).join('');
}
Alternative 1:
you can also use this regex to return an array of the first letter of every word
/(?<=(\s|^))[a-z]/gi
(?<=(\s|^)) is called positive lookbehind which make sure the element in our search pattern is preceded by (\s|^).
so, for your case:
// in case the input is lowercase & there's a word with apostrophe
const toAbbr = (str) => {
return str.match(/(?<=(\s|^))[a-z]/gi)
.join('')
.toUpperCase();
};
toAbbr("java script object notation"); //result JSON
(by the way, there are also negative lookbehind, positive lookahead, negative lookahead, if you want to learn more)
Alternative 2:
match all the words and use replace() method to replace them with the first letter of each word and ignore the space (the method will not mutate your original string)
// in case the input is lowercase & there's a word with apostrophe
const toAbbr = (str) => {
return str.replace(/(\S+)(\s*)/gi, (match, p1, p2) => p1[0].toUpperCase());
};
toAbbr("java script object notation"); //result JSON
// word = not space = \S+ = p1 (p1 is the first pattern)
// space = \s* = p2 (p2 is the second pattern)
It's important to trim the word before splitting it, otherwise, we'd lose some letters.
const getWordInitials = (word: string): string => {
const bits = word.trim().split(' ');
return bits
.map((bit) => bit.charAt(0))
.join('')
.toUpperCase();
};
$ getWordInitials("Java Script Object Notation")
$ "JSON"
How about this:
var str = "", abbr = "";
str = "Java Script Object Notation";
str = str.split(' ');
for (i = 0; i < str.length; i++) {
abbr += str[i].substr(0,1);
}
alert(abbr);
Working Example.
If you came here looking for how to do this that supports non-BMP characters that use surrogate pairs:
initials = str.split(' ')
.map(s => String.fromCodePoint(s.codePointAt(0) || '').toUpperCase())
.join('');
Works in all modern browsers with no polyfills (not IE though)
Getting first letter of any Unicode word in JavaScript is now easy with the ECMAScript 2018 standard:
/(?<!\p{L}\p{M}*)\p{L}/gu
This regex finds any Unicode letter (see the last \p{L}) that is not preceded with any other letter that can optionally have diacritic symbols (see the (?<!\p{L}\p{M}*) negative lookbehind where \p{M}* matches 0 or more diacritic chars). Note that u flag is compulsory here for the Unicode property classes (like \p{L}) to work correctly.
To emulate a fully Unicode-aware \b, you'd need to add a digit matching pattern and connector punctuation:
/(?<!\p{L}\p{M}*|[\p{N}\p{Pc}])\p{L}/gu
It works in Chrome, Firefox (since June 30, 2020), Node.js, and the majority of other environments (see the compatibility matrix here), for any natural language including Arabic.
Quick test:
const regex = /(?<!\p{L}\p{M}*)\p{L}/gu;
const string = "Żerard Łyżwiński";
// Extracting
console.log(string.match(regex)); // => [ "Ż", "Ł" ]
// Extracting and concatenating into string
console.log(string.match(regex).join("")) // => ŻŁ
// Removing
console.log(string.replace(regex, "")) // => erard yżwiński
// Enclosing (wrapping) with a tag
console.log(string.replace(regex, "<span>$&</span>")) // => <span>Ż</span>erard <span>Ł</span>yżwiński
console.log("_Łukasz 1Żukowski".match(/(?<!\p{L}\p{M}*|[\p{N}\p{Pc}])\p{L}/gu)); // => null
In ES6:
function getFirstCharacters(str) {
let result = [];
str.split(' ').map(word => word.charAt(0) != '' ? result.push(word.charAt(0)) : '');
return result;
}
const str1 = "Hello4 World65 123 !!";
const str2 = "123and 456 and 78-1";
const str3 = " Hello World !!";
console.log(getFirstCharacters(str1));
console.log(getFirstCharacters(str2));
console.log(getFirstCharacters(str3));
Output:
[ 'H', 'W', '1', '!' ]
[ '1', '4', 'a', '7' ]
[ 'H', 'W', '!' ]
This should do it.
var s = "Java Script Object Notation",
a = s.split(' '),
l = a.length,
i = 0,
n = "";
for (; i < l; ++i)
{
n += a[i].charAt(0);
}
console.log(n);
The regular expression versions for JavaScript is not compatible with Unicode on older than ECMAScript 6, so for those who want to support characters such as "å" will need to rely on non-regex versions of scripts.
Event when on version 6, you need to indicate Unicode with \u.
More details: https://mathiasbynens.be/notes/es6-unicode-regex
Yet another option using reduce function:
var value = "Java Script Object Notation";
var result = value.split(' ').reduce(function(previous, current){
return {v : previous.v + current[0]};
},{v:""});
$("#output").text(result.v);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="output"/>
This is similar to others, but (IMHO) a tad easier to read:
const getAcronym = title =>
title.split(' ')
.map(word => word[0])
.join('');
ES6 reduce way:
const initials = inputStr.split(' ').reduce((result, currentWord) =>
result + currentWord.charAt(0).toUpperCase(), '');
alert(initials);
Try This Function
const createUserName = function (name) {
const username = name
.toLowerCase()
.split(' ')
.map((elem) => elem[0])
.join('');
return username;
};
console.log(createUserName('Anisul Haque Bhuiyan'));

Reversing a string in JavaScript

I'm trying to reverse an input string
var oneway = document.getElementById('input_field').value();
var backway = oneway.reverse();
but firebug is telling me that oneway.reverse() is not a function. Any ideas?
Thank you
reverse() is a method of array instances. It won't directly work on a string. You should first split the characters of the string into an array, reverse the array and then join back into a string:
var backway = oneway.split("").reverse().join("");
Update
The method above is only safe for "regular" strings. Please see comment by Mathias Bynens below and also his answer for a safe reverse method.
The following technique (or similar) is commonly used to reverse a string in JavaScript:
// Don’t use this!
var naiveReverse = function(string) {
return string.split('').reverse().join('');
}
In fact, all the answers posted so far are a variation of this pattern. However, there are some problems with this solution. For example:
naiveReverse('foo 𝌆 bar');
// → 'rab �� oof'
// Where did the `𝌆` symbol go? Whoops!
If you’re wondering why this happens, read up on JavaScript’s internal character encoding. (TL;DR: 𝌆 is an astral symbol, and JavaScript exposes it as two separate code units.)
But there’s more:
// To see which symbols are being used here, check:
// http://mothereff.in/js-escapes#1ma%C3%B1ana%20man%CC%83ana
naiveReverse('mañana mañana');
// → 'anãnam anañam'
// Wait, so now the tilde is applied to the `a` instead of the `n`? WAT.
A good string to test string reverse implementations is the following:
'foo 𝌆 bar mañana mañana'
Why? Because it contains an astral symbol (𝌆) (which are represented by surrogate pairs in JavaScript) and a combining mark (the ñ in the last mañana actually consists of two symbols: U+006E LATIN SMALL LETTER N and U+0303 COMBINING TILDE).
The order in which surrogate pairs appear cannot be reversed, else the astral symbol won’t show up anymore in the ‘reversed’ string. That’s why you saw those �� marks in the output for the previous example.
Combining marks always get applied to the previous symbol, so you have to treat both the main symbol (U+006E LATIN SMALL LETTER N) as the combining mark (U+0303 COMBINING TILDE) as a whole. Reversing their order will cause the combining mark to be paired with another symbol in the string. That’s why the example output had ã instead of ñ.
Hopefully, this explains why all the answers posted so far are wrong.
To answer your initial question — how to [properly] reverse a string in JavaScript —, I’ve written a small JavaScript library that is capable of Unicode-aware string reversal. It doesn’t have any of the issues I just mentioned. The library is called Esrever; its code is on GitHub, and it works in pretty much any JavaScript environment. It comes with a shell utility/binary, so you can easily reverse strings from your terminal if you want.
var input = 'foo 𝌆 bar mañana mañana';
esrever.reverse(input);
// → 'anañam anañam rab 𝌆 oof'
String.prototype.reverse = function () {
return this.split("").reverse().join("");
}
Inspired by the first result I got when I did a Google for javascript string reverse.
Google harder, bros. This is by Edd Mann.
function reverse (s) {
for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
return o;
}
http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
http://jsperf.com/string-reverse-function-performance
reverse is a function on an array and that is a string. You could explode the string into an array and then reverse it and then combine it back together though.
var str = '0123456789';
var rev_str = str.split('').reverse().join('');
// You could reverse a string without creating an array
String.prototype.reverse= function(){
var s= '', L= this.length;
while(L){
s+= this[--L];
}
return s;
}
var s1= 'the time has come, the walrus said, to speak of many things';
s1.reverse()
/*returned value: (String)
sgniht ynam fo kaeps ot, dias surlaw eht, emoc sah emit eht
*/
This is probably the way, acceptable for all browsers:
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
Call it like a charm:
reverse('your_string');
I like to share some notable implementations for string reverse.
split,reverse,join
const reverseString = (str) => str.split('') .reverse() .join('');
reduce
const reverseString =(str) => [...str].reduce((acc, cur) => cur + acc);
append last one by one
const reverseString = (str) => {
const ary = [];
for(let char of str) {
ary.unshift(char);
}
return ary.join('');
}
recursion
const reverseString =(str)=> (str === '') ? '' : reverseString(str.substr(1)) + str[0];
two pointer approach
const reverseString = (str) => {
const strArr = Array.from(str);
let start = 0;
let end = str.length - 1;
while (start <= end) {
const temp = strArr[start];
strArr[start] = strArr[end];
strArr[end] = temp;
start++;
end--;
}
return strArr.join("");
}
//Using reverse with split, reverse , join
function reverseString1(str) {
return str
.split('') // alternative [...str], Array.from(str)
.reverse() // alternative .sort(() => -1)
.join('');
}
// Using reduce
function reverseString2(str) {
return [...str].reduce((accumulator, current) => current + accumulator) // reduce from left to right
//alternative [...str].reduceRight((accumulator, current) => accumulator + current); // reduce right to left
}
// append to last one by one
function reverseString3(str){
const ary = [];
for(let char of str) {
ary.unshift(char);
}
return ary.join('');
}
// recursion with ternary with substr
function reverseString4(str) {
return (str === '') ? '' : reverseString4(str.substr(1)) + str[0];
}
// two pointer approach [less time complexity O(n)]
// front back chars exchanging
function reverseString5(str) {
const strArr = Array.from(str); // alternative [...str],str.split('')
let start = 0;
let end = str.length - 1;
while (start <= end) {
const temp = strArr[start];
strArr[start] = strArr[end];
strArr[end] = temp;
start++;
end--;
}
return strArr.join("");
}
console.log(reverseString1("Hello World"))
console.log(reverseString2("Hello World"))
console.log(reverseString3("Hello World"))
console.log(reverseString4("Hello World"))
console.log(reverseString5("Hello World"))
//=> dlroW olleH
Note:
Built-in method works well for ASCII inputs, not unicode things.. so use spread operation inspite of split. Check out split vs spread implementation
Extra:
In-Place string reverse is not possible in JS. Check out in-place reverse
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#stringInput").keyup(function () {
debugger;
var string = $("#stringInput").val();
var stringArray = [];
sInput = string.toString();
for (var i = 0, len = sInput.length; i < len; i++) {
stringArray.push(sInput.charAt(i));
}
stringArray.reverse();
str = stringArray.join('');
document.getElementById("stringOutput").value = str;
});
$("button").click(function () {
debugger;
$("#myForm").toggle();
});
});
</script>
</head>
<body>
<div>
<form name="myForm" id="myForm">
<table>
<tr>
<td>Insert Elements :</td>
<td><input type="text" name="stringInput" id="stringInput"/></td>
<td>Output :</td>
<td><input type="text" id="stringOutput" name="stringOutput" readonly="true" /></td>
</tr>
</table>
</form>
<button>Show/Hide</button>
</div>
</body>
</html>
Reverse String using function parameter with error handling :
function reverseString(s)
{
try
{
console.log(s.split("").reverse().join(""));
}
catch(e)
{
console.log(e.message);
console.log(s);
}
}
I think you'll find that in fact reverse() isn't a function in jQuery. Incidentally, jQuery is really good at manipulating your DOM, but isn't really for string manipulation as such (although you can probably get plugins/write your own) to do this.
The best way I've found to reverse a string in javascript is to do the following:
String.prototype.reverse = function(){
splitext = this.split("");
revertext = splitext.reverse();
reversed = revertext.join("");
return reversed;
}
Found at: http://www.bytemycode.com/snippets/snippet/400/
I think you'll find that if you pop the above into your code somewhere, your call to .reverse() should work :)
Mathias Bynens, your code works grate, thanks a lot!
I convert your code to a function, in this way users are able to copy it from here.
Thanks!
//The function reverse a string, JavaScript’s has internal character encoding so we are
//unable to reverse the string in the "easy ways". For example the TL;DR: 𝌆 is an astral
//symbol, and JavaScript exposes it as two separate code units.
function ReverseString(string){
//-
var regexSymbolWithCombiningMarks = /([\0-\u02FF\u0370-\u1DBF\u1E00-\u20CF\u2100-\uD7FF\uDC00-\uFE1F\uFE30-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF])([\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]+)/g;
var regexSurrogatePair = /([\uD800-\uDBFF])([\uDC00-\uDFFF])/g;
//-
//Step 1: deal with combining marks and astral symbols (surrogate pairs)
string = string
//Swap symbols with their combining marks so the combining marks go first
.replace(regexSymbolWithCombiningMarks, function($0, $1, $2) {
return reverse($2) + $1;
})
// Swap high and low surrogates so the low surrogates go first
.replace(regexSurrogatePair, '$2$1');
// Step 2: reverse the code units in the string
var result = '';
var index = string.length;
while (index--) {
result += string.charAt(index);
}
//Return value
return result;
}
This reverse prototype function is implemented using "this".
If you see log console of "this", it will generate the array, and it has length property.
So that it!!! Just use reverse "for-loop" as shown in the code snippet.
String.prototype.reverse = function () {
console.log(this);
var result = "";
var len = this.length;
for (i = (len-1); i >= 0 ; i--) {
result += this[i];
}
return result;
};
alert("elahnu jaknap".reverse());
Use this simple method to reverse the words of a string at its position
function fun(str){
var arr1=str.split(' ');
console.log(arr1);
var strings='',rever='';
for(var i=0;i<arr1.length;i++)
{
strings=arr1[i].split('');
rever+=strings.reverse().join('')+' ';
}
console.log(rever.split(' '));
console.log(rever.trim());
};
fun('javascript is fun');
If it's necessary to revert the string, but return the original value of the error:
function reverseString(s) {
let valuePrintS;
try {
valuePrintS = s.split("").reverse().join("");
} catch {
console.log("s.split is not a function");
valuePrintS = s;
} finally {
console.log(valuePrintS);
}
}
I believe most performant solution with reduce like in https://stackoverflow.com/a/68978553/5018572 post
function reverse(str) {
return str.split("").reduce((final, letter) => letter + final);
}
console.log(reverse("Armaggedon"));
This is how I always do;
var rev = Array.prototype.reduce.call("Hello World",(p,c) => c+p);
console.log(rev);
Some people do it like [].prototype.redu... but that would be creating an array for no reason. Instead use the Array constructor.
Also some people ask why Array.prototype.reverse.call("Hello World") wouldn't work. It's so because .reverse() attempts to reverse the subject array in place and with immutable values in JS such as a String you can not do that.
String.prototype.strReverse = function() {
var newstring = "";
for (var s=0; s < this.length; s++) {
newstring = this.charAt(s) + newstring;
}
return newstring;
};

Categories

Resources