

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>String &#8211; Max的程式語言筆記</title>
	<atom:link href="https://stackoverflow.max-everyday.com/tag/string/feed/" rel="self" type="application/rss+xml" />
	<link>https://stackoverflow.max-everyday.com</link>
	<description>我要當一個豬頭，快樂過每一天</description>
	<lastBuildDate>Sat, 29 Nov 2025 03:04:04 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://stackoverflow.max-everyday.com/wp-content/uploads/2017/02/max-stackoverflow-256.png</url>
	<title>String &#8211; Max的程式語言筆記</title>
	<link>https://stackoverflow.max-everyday.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>[Python] 使用 io.StringIO 進行資料歸一化(normalization)</title>
		<link>https://stackoverflow.max-everyday.com/2025/11/python-io-stringio-normalization/</link>
					<comments>https://stackoverflow.max-everyday.com/2025/11/python-io-stringio-normalization/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Sat, 29 Nov 2025 02:57:41 +0000</pubDate>
				<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=7264</guid>

					<description><![CDATA[情境是有多欄位的資料, 中間分隔是以空格, 但可...]]></description>
										<content:encoded><![CDATA[
<p>情境是有多欄位的資料, 中間分隔是以空格, 但可能有多個空格, 自己做比較慢, python 已有內建的 io 可以處理字串.</p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="583" height="263" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2025/11/2025-11-29_10-51_ga.jpg?v=1764384700" alt="" class="wp-image-7265"/></figure>



<p>範例說明: a 與 b 相隔2個空格, b 與 c 相隔 1 空格, c 與 d 相隔 N 個空格, 最終取得4個元素.</p>



<p>範例:</p>



<pre class="wp-block-code"><code>data_normalized = cookie_data.replace('  ', '\t')
file_like_object = io.StringIO(data_normalized)
for line_number, line in enumerate(file_like_object, 1):
    line = line.strip()
    if not line or line.startswith('#'):
        continue
    parts = line.split()
</code></pre>



<p>這個範例說, # 開頭的行, 資料不要, 其他的分隔後放入 parts array.</p>



<p>完整範例, 轉換 string 為 dicttionary</p>



<pre class="wp-block-code"><code>def parse_netscape_cookies(cookie_data):
    data_normalized = cookie_data.replace('  ', '\t')
    file_like_object = io.StringIO(data_normalized)
    cookies_list = &#91;]
    FIELD_NAMES = &#91;
        "domain",
        "subdomains",
        "path",
        "secure",
        "expiration",
        "name",
        "value"
    ]
    for line_number, line in enumerate(file_like_object, 1):
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        parts = line.split()
        # 預期會有 7 個欄位，如果分割結果不足 7 個，則表示解析錯誤或格式不完整
        if len(parts) &lt; 7:
            print(f"\n&#91;&#x26a0; 警告] 第 {line_number} 行格式不完整，跳過：{line}")
            continue
        cookie_fields = {
            "Line": line_number,
            FIELD_NAMES&#91;0]: parts&#91;0],  # Domain
            FIELD_NAMES&#91;1]: to_bool(parts&#91;1]),  # Include Subdomains (Flag)
            FIELD_NAMES&#91;2]: parts&#91;2],  # Path
            FIELD_NAMES&#91;3]: to_bool(parts&#91;3]),  # Secure (Flag)
            FIELD_NAMES&#91;4]: int(parts&#91;4]),  # Expiration Timestamp
            FIELD_NAMES&#91;5]: parts&#91;5],  # Name
            FIELD_NAMES&#91;6]: parts&#91;6],  # Value
        }
        cookies_list.append(cookie_fields)
    return cookies_list</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2025/11/python-io-stringio-normalization/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>SRT 字幕純文字提取神器：一鍵清除序號與時間軸</title>
		<link>https://stackoverflow.max-everyday.com/2025/11/extract-subtitles-from-srt/</link>
					<comments>https://stackoverflow.max-everyday.com/2025/11/extract-subtitles-from-srt/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Wed, 26 Nov 2025 14:07:40 +0000</pubDate>
				<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=7252</guid>

					<description><![CDATA[你是否曾經需要從 .srt 字幕檔案中提取純文字...]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><img decoding="async" width="1024" height="559" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2025/11/str-to-subtitle-1024x559.jpg" alt="" class="wp-image-7256" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2025/11/str-to-subtitle-1024x559.jpg?v=1764166036 1024w, https://stackoverflow.max-everyday.com/wp-content/uploads/2025/11/str-to-subtitle-600x327.jpg?v=1764166036 600w, https://stackoverflow.max-everyday.com/wp-content/uploads/2025/11/str-to-subtitle-768x419.jpg?v=1764166036 768w, https://stackoverflow.max-everyday.com/wp-content/uploads/2025/11/str-to-subtitle-1536x838.jpg?v=1764166036 1536w, https://stackoverflow.max-everyday.com/wp-content/uploads/2025/11/str-to-subtitle-2048x1117.jpg?v=1764166036 2048w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<p>你是否曾經需要從 <code>.srt</code> 字幕檔案中提取<strong>純文字內容</strong>，卻被惱人的<strong>序號、時間軸</strong>和<strong>空白行</strong>打亂？傳統的文字處理方式容易誤刪內容（例如字幕剛好是數字），效率低落。</p>



<p>本文將介紹一個強大且穩健的 Python 腳本，它採用 SRT 檔案的<strong>區塊結構分析</strong>原理，能夠精準地刪除所有非字幕資訊，完美保留每一句對話。</p>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f3af.png" alt="🎯" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 腳本核心目標</h2>



<p>我們的 Python 腳本將實現以下功能：</p>



<ol start="1" class="wp-block-list">
<li>讀取使用者指定的外部 <code>.srt</code> 檔案。</li>



<li><strong>精準識別</strong>並移除 SRT 檔案中每一組的：
<ul class="wp-block-list">
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 序號行 (例如: <code>1</code>, <code>2</code>)</li>



<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 時間軸行 (例如: <code>00:00:02,680 --> 00:00:04,360</code>)</li>



<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/274c.png" alt="❌" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 所有多餘的空白行。</li>
</ul>
</li>



<li>保留所有字幕內容，即使字幕是純數字也不會誤刪。</li>



<li>將提取出的純文字內容輸出到終端機或指定的新 <code>.txt</code> 檔案。</li>
</ol>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f6e0.png" alt="🛠" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 第一步：準備工作</h2>



<h3 class="wp-block-heading">1. 安裝 Python (如果尚未安裝)</h3>



<p>請確保你的電腦已經安裝了 Python 3 環境。你可以從 <a target="_blank" rel="noreferrer noopener" href="https://www.python.org/downloads/">Python 官網</a> 下載並安裝。</p>



<h3 class="wp-block-heading">2. 儲存腳本</h3>



<p>將以下程式碼儲存為一個檔案，命名為 <code>srt_to_text.py</code>。</p>



<p>Python</p>



<pre class="wp-block-code"><code>import os
import re
import sys

def extract_subtitles_by_block(input_filepath, output_filepath=None):
    """
    讀取一個 .srt 檔案，使用區塊分析模式，精準提取字幕內容。
    """
    if not os.path.exists(input_filepath):
        print(f"&#x274c; 錯誤: 找不到檔案 {input_filepath}")
        return &#91;] if output_filepath is None else None
    
    if not input_filepath.lower().endswith('.srt'):
        print(f"&#x26a0; 警告: 檔案 {input_filepath} 似乎不是 .srt 格式。")

    try:
        # 1. 讀取整個檔案內容
        with open(input_filepath, 'r', encoding='utf-8') as f:
            content = f.read()

        # 2. 以兩個連續的換行符分割成獨立的字幕區塊 (\n\n 或 \r\n\r\n)
        blocks = re.split(r'\n\s*\n|\r\n\s*\r\n', content.strip())
        
        subtitle_lines = &#91;]
        
        for block in blocks:
            if not block.strip():
                continue
            
            # 將區塊內的行按換行符分割
            lines = block.splitlines()
            
            # 依據 SRT 結構，字幕內容從 lines&#91;2] (第三行) 開始
            if len(lines) &gt;= 3:
                for line in lines&#91;2:]:
                    stripped_line = line.strip()
                    # 只添加非空行，處理多行字幕
                    if stripped_line:
                        subtitle_lines.append(stripped_line)
                        
    except Exception as e:
        print(f"&#x274c; 讀取或處理檔案時發生錯誤: {e}")
        return &#91;] if output_filepath is None else None

    # 處理輸出
    if output_filepath:
        try:
            with open(output_filepath, 'w', encoding='utf-8') as outfile:
                outfile.write('\n'.join(subtitle_lines))
            print(f"&#x2705; 成功提取字幕並儲存至：{output_filepath}")
            return None
        except Exception as e:
            print(f"&#x274c; 寫入檔案時發生錯誤: {e}")
            return subtitle_lines
    else:
        return subtitle_lines


def main():
    # 檢查命令行參數
    if len(sys.argv) &lt; 2:
        print("&#x1f4a1; 使用方式:")
        print(f"   python {sys.argv&#91;0]} &lt;輸入的.srt檔案路徑&gt; &#91;輸出的.txt檔案路徑]")
        print("\n範例:")
        print(f"   python {sys.argv&#91;0]} my_video.srt")
        print(f"   python {sys.argv&#91;0]} my_video.srt output.txt")
        return

    input_file = sys.argv&#91;1]
    output_file = None

    if len(sys.argv) &gt; 2:
        output_file = sys.argv&#91;2]
        
    print(f"&#x1f680; 正在處理檔案: {input_file}")
    
    if output_file:
        extract_subtitles_by_block(input_file, output_file)
    else:
        subtitles_list = extract_subtitles_by_block(input_file)
        if subtitles_list:
            print("\n--- 提取出的字幕內容 ---")
            print("\n".join(subtitles_list))
            print("--------------------------")
        elif subtitles_list is not None:
             print("&#x26a0; 提取結果為空，請檢查 .srt 檔案內容。")


if __name__ == '__main__':
    main()
</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading"><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f4bb.png" alt="💻" class="wp-smiley" style="height: 1em; max-height: 1em;" /> 第二步：執行腳本</h2>



<p>打開你的命令提示字元 (Windows) 或終端機 (macOS/Linux)，導航到你存放 <code>srt_to_text.py</code> 的目錄。</p>



<h3 class="wp-block-heading">方式一：列印到終端機 (快速檢視)</h3>



<p>如果你只是想快速查看提取出的純文字內容，不需要存檔，則只提供 SRT 檔案路徑。</p>



<ul class="wp-block-list">
<li><strong>命令格式：</strong> <code>python srt_to_text.py &lt;你的 SRT 檔案名></code></li>
</ul>



<p>Bash</p>



<pre class="wp-block-code"><code># 假設你的字幕檔名為 my_episode.srt
python srt_to_text.py my_episode.srt
</code></pre>



<p><strong>結果輸出：</strong></p>



<pre class="wp-block-code"><code>&#x1f680; 正在處理檔案: my_episode.srt

--- 提取出的字幕內容 ---
放棄台積電的主管
轉到這個跑道上來
那個心中的掙扎應該是蠻大的吧
--------------------------
</code></pre>



<h3 class="wp-block-heading">方式二：儲存到純文字檔案 (永久存檔)</h3>



<p>如果你想將結果儲存為一個新的 <code>.txt</code> 檔案，請在命令後加上你想要的輸出檔名。</p>



<ul class="wp-block-list">
<li><strong>命令格式：</strong> <code>python srt_to_text.py &lt;輸入 SRT 檔案名> &lt;輸出 TXT 檔案名></code></li>
</ul>



<p>Bash</p>



<pre class="wp-block-code"><code># 將 my_episode.srt 的結果儲存到 script_output.txt
python srt_to_text.py my_episode.srt script_output.txt
</code></pre>



<p><strong>結果輸出：</strong></p>



<pre class="wp-block-code"><code>&#x1f680; 正在處理檔案: my_episode.srt
&#x2705; 成功提取字幕並儲存至：script_output.txt
</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">深入理解：腳本為何如此穩健？</h2>



<p>這個腳本的精妙之處在於它不依賴內容猜測，而是利用 SRT 檔案的<strong>固定格式</strong>：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><td><strong>行號</strong></td><td><strong>內容類型</strong></td><td><strong>腳本處理</strong></td></tr></thead><tbody><tr><td>1</td><td>序號 (例如 <code>1</code>)</td><td><strong>忽略</strong> (這是區塊中的第一行)</td></tr><tr><td>2</td><td>時間軸 (例如 <code>00:00 --&gt; ...</code>)</td><td><strong>忽略</strong> (這是區塊中的第二行)</td></tr><tr><td><strong>3</strong></td><td><strong>字幕內容</strong></td><td><strong>保留</strong></td></tr><tr><td>4+</td><td>額外的字幕內容 (多行)</td><td><strong>保留</strong></td></tr></tbody></table></figure>



<p>透過先用空行將整個檔案切割成獨立的「字幕區塊」，再針對每個區塊，我們只需要跳過前兩行，就能確保抓取到的永遠是正確的字幕文字，<strong>完美解決了字幕內容剛好是純數字所導致的誤刪問題</strong>。</p>



<p>現在，你可以輕鬆、快速且精準地將任何 <code>.srt</code> 字幕文件轉換為乾淨的純文字稿了！</p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2025/11/extract-subtitles-from-srt/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>javascript 判斷字串內容為數字</title>
		<link>https://stackoverflow.max-everyday.com/2024/03/javascript-isnumeric/</link>
					<comments>https://stackoverflow.max-everyday.com/2024/03/javascript-isnumeric/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Mon, 04 Mar 2024 05:05:14 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5463</guid>

					<description><![CDATA[字串內容為數字的判斷, 有很多寫法, 又各有優缺...]]></description>
										<content:encoded><![CDATA[
<p>字串內容為數字的判斷, 有很多寫法, 又各有優缺點。用 RegExp 是方法之一, 解法:<br><a href="https://stackoverflow.com/questions/175739/how-can-i-check-if-a-string-is-a-valid-number">https://stackoverflow.com/questions/175739/how-can-i-check-if-a-string-is-a-valid-number</a></p>



<p><strong>2nd October 2020:</strong>&nbsp;note that many bare-bones approaches are fraught with subtle bugs (eg. whitespace, implicit partial parsing, radix, coercion of arrays etc.) that many of the answers here fail to take into account. The following implementation might work for you, but note that it does not cater for number separators other than the decimal point &#8220;<code>.</code>&#8220;:</p>



<pre class="wp-block-code"><code>function isNumeric(str) {
  if (typeof str != "string") return false // we only process strings!  
  return !isNaN(str) &amp;&amp; // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
         !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">To check if a variable (including a string) is a number, check if it is not a number:</h2>



<p>This works regardless of whether the variable content is a string or number.</p>



<pre class="wp-block-code"><code>isNaN(num)         // returns true if the variable does NOT contain a valid number
</code></pre>



<h3 class="wp-block-heading">Examples</h3>



<pre class="wp-block-code"><code>isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true
isNaN('')          // false
isNaN(' ')         // false
isNaN(false)       // false
</code></pre>



<p>Of course, you can negate this if you need to. For example, to implement the&nbsp;<code>IsNumeric</code>&nbsp;example you gave:</p>



<pre class="wp-block-code"><code>function isNumeric(num){
  return !isNaN(num)
}
</code></pre>



<h2 class="wp-block-heading">To convert a string containing a number into a number:</h2>



<p>Only works if the string&nbsp;<em>only</em>&nbsp;contains numeric characters, else it returns&nbsp;<code>NaN</code>.</p>



<pre class="wp-block-code"><code>+num               // returns the numeric value of the string, or NaN 
                   // if the string isn't purely numeric characters
</code></pre>



<h3 class="wp-block-heading">Examples</h3>



<pre class="wp-block-code"><code>+'12'              // 12
+'12.'             // 12
+'12..'            // NaN
+'.12'             // 0.12
+'..12'            // NaN
+'foo'             // NaN
+'12px'            // NaN
</code></pre>



<h2 class="wp-block-heading">To convert a string loosely to a number</h2>



<p>Useful for converting &#8217;12px&#8217; to 12, for example:</p>



<pre class="wp-block-code"><code>parseInt(num)      // extracts a numeric value from the 
                   // start of the string, or NaN.
</code></pre>



<h3 class="wp-block-heading">Examples</h3>



<pre class="wp-block-code"><code>parseInt('12')     // 12
parseInt('aaa')    // NaN
parseInt('12px')   // 12
parseInt('foo2')   // NaN      These last three may
parseInt('12a5')   // 12       be different from what
parseInt('0x10')   // 16       you expected to see.
</code></pre>



<h2 class="wp-block-heading">Floats</h2>



<p>Bear in mind that, unlike&nbsp;<code>+num</code>,&nbsp;<code>parseInt</code>&nbsp;(as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use&nbsp;<code>parseInt()</code>&nbsp;<em>because of</em>&nbsp;this behaviour,&nbsp;<a href="https://parsebox.io/dthree/gyeveeygrngl">you&#8217;re probably better off using another method instead</a>):</p>



<pre class="wp-block-code"><code>+'12.345'          // 12.345
parseInt(12.345)   // 12
parseInt('12.345') // 12
</code></pre>



<h2 class="wp-block-heading">Empty strings</h2>



<p>Empty strings may be a little counter-intuitive.&nbsp;<code>+num</code>&nbsp;converts empty strings or strings with spaces to zero, and&nbsp;<code>isNaN()</code>&nbsp;assumes the same:</p>



<pre class="wp-block-code"><code>+''                // 0
+'   '             // 0
isNaN('')          // false
isNaN('   ')       // false
</code></pre>



<p>But&nbsp;<code>parseInt()</code>&nbsp;does not agree:</p>



<pre class="wp-block-code"><code>parseInt('')       // NaN
parseInt('   ')    // NaN</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>如果是使用 RegExp</p>



<pre class="wp-block-code"><code>function isNumeric(value) {
    return /^-?\d+$/.test(value);
}</code></pre>



<p>這個解法, 遇到 &#8220;0.1&#8221;, 居然會回傳 false, 改用下面的版本, 會好一點:</p>



<pre class="wp-block-code"><code>function isNumber(value) {
  return /^-?\d+(\.\d+)?$/.test(value);
}</code></pre>



<p>使用 isNaN 遇到的問題:</p>



<pre class="wp-block-code"><code>isNaN('foo')       // true
isNaN('10px')      // true</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2024/03/javascript-isnumeric/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>using python, Remove HTML tags/formatting from a string</title>
		<link>https://stackoverflow.max-everyday.com/2023/10/using-python-remove-html-tags-formatting-from-a-string/</link>
					<comments>https://stackoverflow.max-everyday.com/2023/10/using-python-remove-html-tags-formatting-from-a-string/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 06 Oct 2023 09:15:26 +0000</pubDate>
				<category><![CDATA[Python筆記]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[selenium]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=5073</guid>

					<description><![CDATA[在使用 selenium 時, 之前使用 ele...]]></description>
										<content:encoded><![CDATA[
<p>在使用 selenium 時, 之前使用 element.text 都可以正確地取得  TEXT 內容, 很奇怪, 目前使用 selenium 4.13.0 + python 3.9.13 在 Win 10 環境, 有時候會正常, 但有時會失敗, 可以確定取得的內容是正確的, 取得的 innerHTML 長這樣:</p>



<pre class="wp-block-code"><code>&lt;div data-v-337697a8="" class="sesstion-item">&lt;div data-v-337697a8="" class="row pa-4 flex-column flex-sm-row no-gutters">&lt;div data-v-337697a8="" class="col-sm-10 col-md-10 col-12">&lt;div data-v-337697a8="" class="row mx-0 flex-column flex-md-row no-gutters">&lt;div data-v-337697a8="" class="d-flex text-left font-weight-bold text-regular py-2 is-word-break col-sm-12 col-md-4 col-12 align-self-center">
                2023 JO1 1ST ASIA TOUR 'BEYOND THE DARK' LIMITED EDITION IN TAIPEI
              &lt;/div>&lt;div data-v-337697a8="" class="px-md-2 d-flex justify-md-center align-left align-md-center col-sm-12 col-md-2 col-12">&lt;div data-v-337697a8="" class="d-flex mb-2 mb-md-0">&lt;div data-v-337697a8="" class="grey--text text--darken-1 d-block d-md-none mr-2 wordBreakKeepAll">日期&lt;/div>&lt;div data-v-337697a8="">2023-11-11(六)&lt;/div>&lt;/div>&lt;/div>&lt;div data-v-337697a8="" class="px-md-2 d-flex justify-md-center align-md-center col-sm-12 col-md-2 col-12">&lt;div data-v-337697a8="" class="d-flex mb-2 mb-md-0">&lt;div data-v-337697a8="" class="grey--text text--darken-1 d-block d-md-none mr-2 wordBreakKeepAll">時間&lt;/div>&lt;div data-v-337697a8="">19:00&lt;/div>&lt;/div>&lt;/div>&lt;div data-v-337697a8="" class="px-md-2 d-flex justify-md-center align-md-center is-word-break col-sm-12 col-md-4 col-12">&lt;div data-v-337697a8="" class="d-flex mb-2 mb-md-0">&lt;div data-v-337697a8="" class="grey--text text--darken-1 d-block d-md-none mr-2 wordBreakKeepAll">地點&lt;/div>&lt;div data-v-337697a8="" class="text-left text-md-center location-content">
                    Zepp New Taipei
                    &lt;div data-v-337697a8="" class="grey--text text--darken-3 text-small d-inline d-md-block">
                      新北市新莊區新北大道四段3號8樓
                    &lt;/div>&lt;/div>&lt;/div>&lt;/div>&lt;/div>&lt;/div>&lt;div data-v-337697a8="" class="font-weight-bold col-sm-2 col-md-2 col-12 align-self-center">&lt;hr data-v-337697a8="" role="separator" aria-orientation="horizontal" class="d-block d-sm-none mb-5 mt-3 v-divider theme--light">&lt;div data-v-9536f93e="" data-v-337697a8="">&lt;!---->&lt;!---->&lt;!---->&lt;!---->&lt;button data-v-9536f93e="" type="button" class="nextBtn float-right v-btn v-btn--block v-btn--has-bg v-btn--rounded theme--dark v-size--default">&lt;span class="v-btn__content">立即購票&lt;/span>&lt;/button>&lt;!---->&lt;/div>&lt;/div>&lt;/div>&lt;!---->&lt;/div></code></pre>



<p>使用 .text 取得內容, 居然是空值! 但多試幾次, 偶爾可以取得正確的 text, 既然可以拿 innerHTML 就自己來去 tag 就好了. </p>



<pre class="wp-block-code"><code>import re
def striphtml(data):
    p = re.compile(r'&lt;.*?>')
    return p.sub('', data)

>>> striphtml('&lt;a href="foo.com" class="bar">I Want This &lt;b>text!&lt;/b>&lt;/a>')
'I Want This text!'</code></pre>



<p>Below you will find the syntax which require as per different binding. Change the&nbsp;<code>innerHTML</code>&nbsp;to&nbsp;<code>outerHTML</code>&nbsp;as per required.</p>



<p>Python:</p>



<pre class="wp-block-code"><code>element.get_attribute('innerHTML')</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2023/10/using-python-remove-html-tags-formatting-from-a-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Converting arraybuffer to string : Maximum call stack size exceeded</title>
		<link>https://stackoverflow.max-everyday.com/2023/07/converting-arraybuffer-to-string-maximum-call-stack-size-exceeded/</link>
					<comments>https://stackoverflow.max-everyday.com/2023/07/converting-arraybuffer-to-string-maximum-call-stack-size-exceeded/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 07 Jul 2023 07:32:28 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=4923</guid>

					<description><![CDATA[在轉換 arraybuffer 為 String...]]></description>
										<content:encoded><![CDATA[
<p>在轉換 arraybuffer  為 String 時, 出錯, length 小的時候, 不會出問題, 但大量時就出錯了:</p>



<pre class="wp-block-preformatted">Maximum call stack size exceeded</pre>



<figure class="wp-block-image size-full"><img decoding="async" width="724" height="240" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2023/07/2023-07-07-14_31_17-Window.jpg" alt="" class="wp-image-4924" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2023/07/2023-07-07-14_31_17-Window.jpg?v=1688711556 724w, https://stackoverflow.max-everyday.com/wp-content/uploads/2023/07/2023-07-07-14_31_17-Window-600x199.jpg?v=1688711556 600w" sizes="(max-width: 724px) 100vw, 724px" /></figure>



<p></p>



<p>To work around the problem you could batch the calls to <code>String.fromCharCode</code>. Don’t call it just once, but call it once for every 1024 entries, for example, and then concatenate the resulting strings.</p>



<p>會造成錯誤的程式碼:</p>



<pre class="wp-block-code"><code>let data_array = pako.inflate(raw);
let str = String.fromCharCode.apply(null, new Uint16Array(data_array))</code></pre>



<p>改寫成, 不會出錯的版本:</p>



<pre class="wp-block-code"><code>let str = '';
const chunk = 8 * 1024
let i;
for (i = 0; i &lt; data_array.length / chunk; i++) {
	str += String.fromCharCode.apply(null, data_array.slice(i * chunk, (i + 1) * chunk));
}
str += String.fromCharCode.apply(null, data_array.slice(i * chunk));</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>相關討論:<br>Converting arraybuffer to string : Maximum call stack size exceeded<br><a href="https://stackoverflow.com/questions/38432611/converting-arraybuffer-to-string-maximum-call-stack-size-exceeded">https://stackoverflow.com/questions/38432611/converting-arraybuffer-to-string-maximum-call-stack-size-exceeded</a></p>



<p>I finally used&nbsp;<a href="https://stackoverflow.com/a/9458996/535203">this code</a>:</p>



<pre class="wp-block-code"><code>function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i &lt; len; i++) {
        binary += String.fromCharCode( bytes&#91; i ] );
    }
    return window.btoa( binary );
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2023/07/converting-arraybuffer-to-string-maximum-call-stack-size-exceeded/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Decompress gzip and zlib string in javascript</title>
		<link>https://stackoverflow.max-everyday.com/2023/07/decompress-gzip-and-zlib-string-in-javascript/</link>
					<comments>https://stackoverflow.max-everyday.com/2023/07/decompress-gzip-and-zlib-string-in-javascript/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 07 Jul 2023 02:55:05 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=4918</guid>

					<description><![CDATA[想在 javascript 解壓縮 zip 檔,...]]></description>
										<content:encoded><![CDATA[
<p>想在 javascript 解壓縮 zip 檔, 解法:<br><a href="https://stackoverflow.com/questions/14620769/decompress-gzip-and-zlib-string-in-javascript">https://stackoverflow.com/questions/14620769/decompress-gzip-and-zlib-string-in-javascript</a></p>



<p><a href="https://github.com/nodeca/pako">Pako</a>&nbsp;is a full and modern&nbsp;<code>Zlib</code>&nbsp;port.</p>



<p>Here is a very simple example and you can work from there.</p>



<p>Get&nbsp;<a href="https://raw.githubusercontent.com/nodeca/pako/master/dist/pako.js">pako.js</a>&nbsp;and you can decompress byteArray like so:</p>



<pre class="wp-block-code"><code>&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Gunzipping binary gzipped string&lt;/title&gt;
  &lt;script type="text/javascript" src="pako.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;

    // Get datastream as Array, for example:
    var charData    = &#91;31,139,8,0,0,0,0,0,0,3,5,193,219,13,0,16,16,4,192,86,214,151,102,52,33,110,35,66,108,226,60,218,55,147,164,238,24,173,19,143,241,18,85,27,58,203,57,46,29,25,198,34,163,193,247,106,179,134,15,50,167,173,148,48,0,0,0];

    // Turn number array into byte-array
    var binData     = new Uint8Array(charData);

    // Pako magic
    var data        = pako.inflate(binData);

    // Convert gunzipped byteArray back to ascii string:
    var strData     = String.fromCharCode.apply(null, new Uint16Array(data));

    // Output to console
    console.log(strData);

  &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    Open up the developer console.
&lt;/body&gt;
&lt;/html&gt;
</code></pre>



<p>Running example:&nbsp;<a href="http://jsfiddle.net/9yH7M/">http://jsfiddle.net/9yH7M/</a></p>



<p>Alternatively you can base64 encode the array before you send it over as the Array takes up a lot of overhead when sending as JSON or XML. Decode likewise:</p>



<pre class="wp-block-code"><code>// Get some base64 encoded binary data from the server. Imagine we got this:
var b64Data     = 'H4sIAAAAAAAAAwXB2w0AEBAEwFbWl2Y0IW4jQmziPNo3k6TuGK0Tj/ESVRs6yzkuHRnGIqPB92qzhg8yp62UMAAAAA==';

// Decode base64 (convert ascii to binary)
var strData     = atob(b64Data);

// Convert binary string to character-number array
var charData    = strData.split('').map(function(x){return x.charCodeAt(0);});

// Turn number array into byte-array
var binData     = new Uint8Array(charData);

// Pako magic
var data        = pako.inflate(binData);

// Convert gunzipped byteArray back to ascii string:
var strData     = String.fromCharCode.apply(null, new Uint16Array(data));

// Output to console
console.log(strData);
</code></pre>



<p>Running example:&nbsp;<a href="http://jsfiddle.net/9yH7M/1/">http://jsfiddle.net/9yH7M/1/</a></p>



<p>To go more advanced, here is the&nbsp;<a href="http://nodeca.github.io/pako/"><code>pako</code>&nbsp;API documentation</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2023/07/decompress-gzip-and-zlib-string-in-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>compression and decompression of string data in java</title>
		<link>https://stackoverflow.max-everyday.com/2023/07/compression-and-decompression-of-string-data-in-java/</link>
					<comments>https://stackoverflow.max-everyday.com/2023/07/compression-and-decompression-of-string-data-in-java/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Fri, 07 Jul 2023 02:53:33 +0000</pubDate>
				<category><![CDATA[Java筆記]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=4916</guid>

					<description><![CDATA[想傳文字格式檔案到client, 沒壓縮要傳很久...]]></description>
										<content:encoded><![CDATA[
<p>想傳文字格式檔案到client, 沒壓縮要傳很久, 所以想在 java 裡先壓縮, 再傳, 解法:<br><a href="https://stackoverflow.com/questions/16351668/compression-and-decompression-of-string-data-in-java">https://stackoverflow.com/questions/16351668/compression-and-decompression-of-string-data-in-java</a></p>



<p>if we are trying to decompress a uncompressed(&#8220;not a zip format&#8221;) byte[] . we will get &#8220;Not in GZIP format&#8221; exception message.</p>



<p>For solving that we can add addition code in our Class.</p>



<pre class="wp-block-code"><code>public static boolean isCompressed(final byte&#91;] compressed) {
    return (compressed&#91;0] == (byte) (GZIPInputStream.GZIP_MAGIC)) &amp;&amp; (compressed&#91;1] == (byte) (GZIPInputStream.GZIP_MAGIC &gt;&gt; 8));
}
</code></pre>



<p>My Complete Compression Class with compress/decompress would look like:</p>



<pre class="wp-block-code"><code>import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPCompression {
  public static byte&#91;] compress(final String str) throws IOException {
    if ((str == null) || (str.length() == 0)) {
      return null;
    }
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(str.getBytes("UTF-8"));
    gzip.flush();
    gzip.close();
    return obj.toByteArray();
  }

  public static String decompress(final byte&#91;] compressed) throws IOException {
    final StringBuilder outStr = new StringBuilder();
    if ((compressed == null) || (compressed.length == 0)) {
      return "";
    }
    if (isCompressed(compressed)) {
      final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
      final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

      String line;
      while ((line = bufferedReader.readLine()) != null) {
        outStr.append(line);
      }
    } else {
      outStr.append(compressed);
    }
    return outStr.toString();
  }

  public static boolean isCompressed(final byte&#91;] compressed) {
    return (compressed&#91;0] == (byte) (GZIPInputStream.GZIP_MAGIC)) &amp;&amp; (compressed&#91;1] == (byte) (GZIPInputStream.GZIP_MAGIC &gt;&gt; 8));
  }
}</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>也可以使用下面這個比較易懂:</p>



<pre class="wp-block-code"><code>import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class PakoGzipUtils {
    public static String compress(String str) throws IOException {
        if (str == null || str.length() == 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes());
        gzip.close();
        return out.toString("ISO-8859-1");
    }
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2023/07/compression-and-decompression-of-string-data-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>JavaScript Program to Check if a Number is Float or Integer</title>
		<link>https://stackoverflow.max-everyday.com/2023/07/javascript-program-to-check-if-a-number-is-float-or-integer/</link>
					<comments>https://stackoverflow.max-everyday.com/2023/07/javascript-program-to-check-if-a-number-is-float-or-integer/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Thu, 06 Jul 2023 07:07:16 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=4914</guid>

					<description><![CDATA[檢查字串是否為數字內容, 在 javascrip...]]></description>
										<content:encoded><![CDATA[
<p>檢查字串是否為數字內容, 在 javascript 裡有很多方法:<br><a href="https://stackoverflow.com/questions/175739/how-can-i-check-if-a-string-is-a-valid-number">https://stackoverflow.com/questions/175739/how-can-i-check-if-a-string-is-a-valid-number</a></p>



<pre class="wp-block-code"><code>function isNumeric(str) {
  if (typeof str != "string") return false // we only process strings!  
  return !isNaN(str) &amp;&amp; // use type coercion to parse the _entirety_ of the string (`parseFloat` alone does not do this)...
         !isNaN(parseFloat(str)) // ...and ensure strings of whitespace fail
}
</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<h2 class="wp-block-heading">To check if a variable (including a string) is a number, check if it is not a number:</h2>



<p>This works regardless of whether the variable content is a string or number.</p>



<pre class="wp-block-code"><code>isNaN(num)         // returns true if the variable does NOT contain a valid number
</code></pre>



<h3 class="wp-block-heading">Examples</h3>



<pre class="wp-block-code"><code>isNaN(123)         // false
isNaN('123')       // false
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true
isNaN('10px')      // true
isNaN('')          // false
isNaN(' ')         // false
isNaN(false)       // false
</code></pre>



<p>Of course, you can negate this if you need to. For example, to implement the&nbsp;<code>IsNumeric</code>&nbsp;example you gave:</p>



<pre class="wp-block-code"><code>function isNumeric(num){
  return !isNaN(num)
}
</code></pre>



<h2 class="wp-block-heading">To convert a string containing a number into a number:</h2>



<p>Only works if the string&nbsp;<em>only</em>&nbsp;contains numeric characters, else it returns&nbsp;<code>NaN</code>.</p>



<pre class="wp-block-code"><code>+num               // returns the numeric value of the string, or NaN 
                   // if the string isn't purely numeric characters
</code></pre>



<h3 class="wp-block-heading">Examples</h3>



<pre class="wp-block-code"><code>+'12'              // 12
+'12.'             // 12
+'12..'            // NaN
+'.12'             // 0.12
+'..12'            // NaN
+'foo'             // NaN
+'12px'            // NaN
</code></pre>



<h2 class="wp-block-heading">To convert a string loosely to a number</h2>



<p>Useful for converting &#8217;12px&#8217; to 12, for example:</p>



<pre class="wp-block-code"><code>parseInt(num)      // extracts a numeric value from the 
                   // start of the string, or NaN.
</code></pre>



<h3 class="wp-block-heading">Examples</h3>



<pre class="wp-block-code"><code>parseInt('12')     // 12
parseInt('aaa')    // NaN
parseInt('12px')   // 12
parseInt('foo2')   // NaN      These last three may
parseInt('12a5')   // 12       be different from what
parseInt('0x10')   // 16       you expected to see.
</code></pre>



<h2 class="wp-block-heading">Floats</h2>



<p>Bear in mind that, unlike&nbsp;<code>+num</code>,&nbsp;<code>parseInt</code>&nbsp;(as the name suggests) will convert a float into an integer by chopping off everything following the decimal point (if you want to use&nbsp;<code>parseInt()</code>&nbsp;<em>because of</em>&nbsp;this behaviour,&nbsp;<a href="https://parsebox.io/dthree/gyeveeygrngl">you&#8217;re probably better off using another method instead</a>):</p>



<pre class="wp-block-code"><code>+'12.345'          // 12.345
parseInt(12.345)   // 12
parseInt('12.345') // 12
</code></pre>



<h2 class="wp-block-heading">Empty strings</h2>



<p>Empty strings may be a little counter-intuitive.&nbsp;<code>+num</code>&nbsp;converts empty strings or strings with spaces to zero, and&nbsp;<code>isNaN()</code>&nbsp;assumes the same:</p>



<pre class="wp-block-code"><code>+''                // 0
+'   '             // 0
isNaN('')          // false
isNaN('   ')       // false
</code></pre>



<p>But&nbsp;<code>parseInt()</code>&nbsp;does not agree:</p>



<pre class="wp-block-code"><code>parseInt('')       // NaN
parseInt('   ')    // NaN</code></pre>



<hr class="wp-block-separator has-alpha-channel-opacity"/>



<p>Check if a value is a Float or an Integer in JavaScript<br><a href="https://bobbyhadz.com/blog/javascript-check-if-value-is-float">https://bobbyhadz.com/blog/javascript-check-if-value-is-float</a></p>



<p>檢查是否為浮點數:</p>



<pre class="wp-block-code"><code><em>// &#x2705; check if a value is a float</em>
function isFloat(value) {
  if (
    typeof value === 'number' &amp;&amp;
    !Number.isNaN(value) &amp;&amp;
    !Number.isInteger(value)
  ) {
    return true;
  }

  return false;
}

console.log(isFloat(1)); <em>// &#x1f449; false</em>
console.log(isFloat(1.5)); <em>// &#x1f449; true</em>
console.log(isFloat(-1.5)); <em>// &#x1f449; true</em>
console.log(isFloat('1.5')); <em>// &#x1f449; false</em></code></pre>



<p></p>



<p>檢查是否為整數:</p>



<pre class="wp-block-code"><code>function isInteger(value) {
  return /^-?&#91;0-9]+$/.test(value);
}

console.log(isInteger(12)); <em>// &#x1f449; true</em>
console.log(isInteger(-12)); <em>// &#x1f449; true</em>
console.log(isInteger(1.0)); <em>// &#x1f449; true</em>
console.log(isInteger('1')); <em>// &#x1f449; true</em>
console.log(isInteger(1.5)); <em>// &#x1f449; false</em></code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2023/07/javascript-program-to-check-if-a-number-is-float-or-integer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>javascript convert string to number or float</title>
		<link>https://stackoverflow.max-everyday.com/2023/07/javascript-convert-string-to-number-or-float/</link>
					<comments>https://stackoverflow.max-everyday.com/2023/07/javascript-convert-string-to-number-or-float/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Thu, 06 Jul 2023 07:01:03 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=4911</guid>

					<description><![CDATA[javascript variable 轉成 i...]]></description>
										<content:encoded><![CDATA[
<p>javascript variable 轉成 integer:</p>



<pre class="wp-block-code"><code>let float = parseInt(string, 10);</code></pre>



<p></p>



<p>javascript variable 轉成 float:</p>



<pre class="wp-block-code"><code>let float = parseFloat(string);</code></pre>



<p></p>



<p>javascript variable 轉成 numeber:</p>



<pre class="wp-block-code"><code>let float = new Number(string);</code></pre>



<p>除此之外, 還有2個神奇的操作:<br><a href="https://stackoverflow.com/questions/33544827/convert-string-to-either-integer-or-float-in-javascript">https://stackoverflow.com/questions/33544827/convert-string-to-either-integer-or-float-in-javascript</a></p>



<p>Multiply string which has number data with 1. You will get the&nbsp;<strong>Numeric</strong>&nbsp;data value.</p>



<pre class="wp-block-code"><code>var int_value = "string" * 1;
</code></pre>



<p>In your case</p>



<pre class="wp-block-code"><code>a = '2' * 1; // =&gt; parse to integer
b = '2.1' * 1; // =&gt; parse to float
c = '2.0' * 1; // =&gt; parse to float
d = 'text' * 1; // =&gt; don't parse    //NaN value
</code></pre>



<p>For last one you will get <code>NaN</code> value. Manually handle for NaN value.</p>



<p>以及使用 eval():<br><a href="https://www.tutorialspoint.com/how-to-convert-string-into-float-in-javascript">https://www.tutorialspoint.com/how-to-convert-string-into-float-in-javascript</a></p>



<pre class="wp-block-code"><code>      let string = "3.456"; 
      let float = eval(string);</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2023/07/javascript-convert-string-to-number-or-float/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to easily truncate an array with JavaScript?</title>
		<link>https://stackoverflow.max-everyday.com/2023/05/how-to-easily-truncate-an-array-with-javascript/</link>
					<comments>https://stackoverflow.max-everyday.com/2023/05/how-to-easily-truncate-an-array-with-javascript/#respond</comments>
		
		<dc:creator><![CDATA[max-stackoverflow]]></dc:creator>
		<pubDate>Thu, 11 May 2023 08:48:53 +0000</pubDate>
				<category><![CDATA[javascript筆記]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://stackoverflow.max-everyday.com/?p=4814</guid>

					<description><![CDATA[我有一個類似 stack 的 array , 想...]]></description>
										<content:encoded><![CDATA[
<p>我有一個類似 stack 的  array , 想只保留 array 裡的前N筆. </p>



<p>使用的情境是有一個檔案瀏覽時的 nav, 當不是最後一個項目時, 要允許使用者pop 到目的的階層:</p>



<figure class="wp-block-image size-full"><img loading="lazy" decoding="async" width="850" height="466" src="https://stackoverflow.max-everyday.com/wp-content/uploads/2023/05/2023-05-11-16_46_53-Workflow-Editor.jpg" alt="" class="wp-image-4815" srcset="https://stackoverflow.max-everyday.com/wp-content/uploads/2023/05/2023-05-11-16_46_53-Workflow-Editor.jpg?v=1683794886 850w, https://stackoverflow.max-everyday.com/wp-content/uploads/2023/05/2023-05-11-16_46_53-Workflow-Editor-600x329.jpg?v=1683794886 600w, https://stackoverflow.max-everyday.com/wp-content/uploads/2023/05/2023-05-11-16_46_53-Workflow-Editor-768x421.jpg?v=1683794886 768w" sizes="auto, (max-width: 850px) 100vw, 850px" /></figure>



<p>解法:<br><a href="https://stackoverflow.com/questions/953071/how-to-easily-truncate-an-array-with-javascript">https://stackoverflow.com/questions/953071/how-to-easily-truncate-an-array-with-javascript</a></p>



<p>There is a&nbsp;<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice">slice</a>&nbsp;method</p>



<pre class="wp-block-code"><code>let arr = &#91;1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = arr.slice(0, 4);
console.log(arr);</code></pre>



<p>使用範例: <br>PS: 這個使用起來, 有一點點像 python 的 array 裡的用法, 例如: 負數指從右邊數過來.</p>



<pre class="wp-block-code"><code>const animals = &#91;'ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Expected output: Array &#91;"camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array &#91;"camel", "duck"]

console.log(animals.slice(1, 5));
// Expected output: Array &#91;"bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array &#91;"duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array &#91;"camel", "duck"]

console.log(animals.slice());
// Expected output: Array &#91;"ant", "bison", "camel", "duck", "elephant"]</code></pre>



<p>跟 .slice() 很像的是多一個p 的 splice().<br><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice</a></p>



<p>使用範例:</p>



<pre class="wp-block-code"><code>Remove 0 (zero) elements before index 2, and insert "drum"
const myFish = &#91;"angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2, 0, "drum");

// myFish is &#91;"angel", "clown", "drum", "mandarin", "sturgeon"]
// removed is &#91;], no elements removed
Copy to Clipboard
Remove 0 (zero) elements before index 2, and insert "drum" and "guitar"
const myFish = &#91;"angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2, 0, "drum", "guitar");

// myFish is &#91;"angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
// removed is &#91;], no elements removed
Copy to Clipboard
Remove 1 element at index 3
const myFish = &#91;"angel", "clown", "drum", "mandarin", "sturgeon"];
const removed = myFish.splice(3, 1);

// myFish is &#91;"angel", "clown", "drum", "sturgeon"]
// removed is &#91;"mandarin"]
Copy to Clipboard
Remove 1 element at index 2, and insert "trumpet"
const myFish = &#91;"angel", "clown", "drum", "sturgeon"];
const removed = myFish.splice(2, 1, "trumpet");

// myFish is &#91;"angel", "clown", "trumpet", "sturgeon"]
// removed is &#91;"drum"]
Copy to Clipboard
Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"
const myFish = &#91;"angel", "clown", "trumpet", "sturgeon"];
const removed = myFish.splice(0, 2, "parrot", "anemone", "blue");

// myFish is &#91;"parrot", "anemone", "blue", "trumpet", "sturgeon"]
// removed is &#91;"angel", "clown"]
Copy to Clipboard
Remove 2 elements, starting from index 2
const myFish = &#91;"parrot", "anemone", "blue", "trumpet", "sturgeon"];
const removed = myFish.splice(2, 2);

// myFish is &#91;"parrot", "anemone", "sturgeon"]
// removed is &#91;"blue", "trumpet"]
Copy to Clipboard
Remove 1 element from index -2
const myFish = &#91;"angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(-2, 1);

// myFish is &#91;"angel", "clown", "sturgeon"]
// removed is &#91;"mandarin"]
Copy to Clipboard
Remove all elements, starting from index 2
const myFish = &#91;"angel", "clown", "mandarin", "sturgeon"];
const removed = myFish.splice(2);

// myFish is &#91;"angel", "clown"]
// removed is &#91;"mandarin", "sturgeon"]</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://stackoverflow.max-everyday.com/2023/05/how-to-easily-truncate-an-array-with-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
